So I created a class called myClass that takes in an int and has a private variable that stores the int as a vector in binary (i.e. 12 is '1100'). I want to define an operator that adds two myClass variables together as a vector of bools (aka bit-wise operation).
Here is the code I have:
class myClass {
public:
myClass();
myClass(int a);
myClass& operator+(const myClass& value);
private:
std::vector<bool> bit;
};
I want this to work in the main function:
int main() {
std::cin >> value;
Integer a = value;
std::cin >> value;
Integer b = value;
myClass c = a+b;
return 0;
}
Operator definition:
myClass myClass::operator+(const myClass& rhs) {
Integer c = // not sure what to do here
return c;
}
The part that's confusing me is that it must take in an integer but then the operator does the operation on the vector of bools.
Well obviously you need to do the same as when you add normal numbers on paper. Start with the lowest significance bits, and add them together. If the result overflows (eg. binary 1+1=10) then remember that overflow for the next iteration.
I'd strongly suggest that you first create constructor that takes bool array for your class:
myClass(std::vector<bool> bits);
We'll use that in the implementation. Now what you want is to add the lists of bools. I have created an implementation that doesn't care how big the lists are. This will be handy if you want to calculate with huge integers:
#include <vector>
bool add_bools(const bool A, const bool B) {
return !(A && B) && (A || B);
}
/** Loops over vectors and adds the booleans in them
the booleans are considered to be in little endian order
so that the least significant is first in the array. **/
std::vector<bool> add_vectors(const std::vector<bool>& first,
const std::vector<bool>& second) {
std::vector<bool> result;
// Remembers that previous addition produced false when
// we add true+true
bool overflow = false;
const int bits = first.size()>second.size()?first.size():second.size();
for (int i = 0; i < bits || overflow; ++i) {
bool bitA, bitB;
bitA = i<first.size() ? first[i]:false;
bitB = i<second.size() ? second[i]:false;
bool tmp_result = add_bools(bitA, bitB);
// remember to add overflow from previous iteration
result.push_back(add_bools(tmp_result, overflow));
// remember overflow for next iteration
overflow = (bitA&&bitB) || (overflow && tmp_result);
}
return result;
}
#include <iostream>
void test_add_vectors() {
std::vector<bool> first;
std::vector<bool> second;
const int bits = 5;
for (int i = 0, l = bits; i < l; ++i) {
first.push_back(false);
second.push_back(true);
}
first[0] = true;
std::vector<bool> result = add_vectors(first, second);
for (int i = 0, l = result.size(); i < l; ++i) {
std::cout<< (result[i]?'1':'0')<<" ";
}
}
You can use that implementation like this, making use of the constructor that takes bool array:
myClass myClass::operator+(const myClass& rhs) {
myClass result(add_vectors(bit, rhs.bit));
return result;
}
You need to define a way to go to and from an integer representation. Here's a rough idea:
#include <vector>
#include <iostream>
class myClass {
private:
void setInt(int x) {
bit.clear();
while (x) {
if (x & 1)
bit.push_back(1);
else
bit.push_back(0);
x>>=1;
}
reverse(bit.begin(), bit.end());
}
public:
int toInt() const {
int i = 0;
for (size_t b = 0; b < bit.size(); b++) {
if (bit[bit.size() - 1 - b])
i |= 1<<b;
}
return i;
}
myClass(int a) {
setInt(a);
}
myClass& operator+(const myClass& value) {
setInt(toInt() + value.toInt());
return *this;
}
private:
std::vector<bool> bit;
};
int main() {
myClass c(10);
myClass d(20);
std::cout << "c=" << c.toInt() << "\n";
std::cout << "d=" << d.toInt() << "\n";
std::cout << "Sum=" << (c + d).toInt() << "\n";
}
`myClass c = a+b;`
Since a and b are both declared as Integer, this line will call operator+(const Integer& x, const Integer& y) or Integer::operator+(const Integer& x). The only way it will call myClass::operator+(const myClass& rhs) is if you have a conversion constructor myClass::myClass(const Integer& i).
Related
I have a class and i keep getting some error from the destructor.
This is the clas:
#pragma once
class Number
{
int bas;
char* val;
public:
Number(const char* value, int base);
Number(const Number& x);
~Number();
void SwitchBase(int newBase);
void Print();
int GetDigitsCount();
int GetBase();
};
This is the cpp file:
#include "Number.h"
#include <iostream>
Number::Number(const char* value, int base)
{
int a = -1;
do
{
a++;
} while (value[a] != '\0');
val = new char[a + 1];
for (int i = 0; i <= a; i++)
val[i] = value[i];
bas = base;
}
Number::Number(const Number& x)
{
int a = -1;
bas = x.bas;
do
{
a++;
} while (x.val[a] != '\0');
delete[]val;
val = new char[a + 1];
int i;
for (i = 0; i <= a; i++)
val[i] = x.val[i];
}
Number::~Number()
{
delete[]val;
}
void Number::Print()
{
std::cout << "Numarul este: " << val<< std::endl << "Baza este: " << bas<<std::endl;
}
int Number:: GetDigitsCount()
{
int l = 0;
do
{
l++;
} while (val[l] != '\0');
return l;
}
This is the main:
int main()
{
Number x("123", 10),y("111",10),z("0",10);
z = y;
z.Print();
}
I keep getting this error:
Invalid address specified to RtlValidateHeap( 010C0000, 010C8DD8 )
If i do this change in main it works properly but it is not really what I want...
int main()
{
Number x("123", 10),y("111",10);
Number z = y;
z.Print();
}
How can I solve this? I can't figure it out...
Your Number class is missing an assignment operator. Since you use the assignment operator in main the default assignment operator will cause a double delete when you exit main and this explains the error.
It also explains why the error goes away when you change main to use the copy constructor instead of the assignment operator.
You should look at the copy and swap idiom to show how to easily and efficiently implement copy constructors and assignment operators.
Alternatively you could also use std::string instead of manually allocating memory. This would eliminate the need to write a destructor, copy constructor and assignment operator. That's the best solution.
This is an example of how code may look like using std::string:
#include <iostream>
#include <string>
class Number
{
int bas;
std::string val;
public:
Number(std::string, int base);
Number(const Number& number);
Number& operator= (const Number& number);
~Number()=default;
void Print();
int GetDigitsCount();
};
Number::Number(std::string value, int base)
{
val=value;
bas=base;
}
Number::Number(const Number& number)
{
val=number.val;
bas=number.bas;
}
Number& Number::operator= (const Number& number)
{
val=number.val;
bas=number.bas;
return *this;
}
void Number::Print()
{
std::cout << "Numarul este: " << val<< std::endl << "Baza este: " << bas<<std::endl;
}
int Number:: GetDigitsCount()
{
return val.size();
}
int main()
{
Number x("123", 10),y("111",10),z("0",10);
Number k(y);
k.Print();
}
Say I have a simple vector class, vec:
#include <iostream>
#include <stdlib.h>
class vec {
public:
vec() {}
// Constructor.
vec(int n) {
len = n;
data = new double[len];
}
// Destructor.
~vec() { delete [] data; }
// Accessor.
double & operator[](int i) const {
check_index(i);
return data[i];
}
// Other methods...
// ....
protected:
int len;
double * data;
void check_index(int i) const {
if(i < 0 || i >= len) {
std::cerr << "Bad access.\n";
exit(1);
}
}
};
Now suppose I have a special type of vector with sparse structure, e.g., where every even-index is zero. Call this oddvec. Instances of oddvec should be declared just as with the vec class, but underneath, the memory use should be efficient since only half the data is non-zero.
The accessor for the oddvec class should return 0 if the index is even, and return the odd-index element (stored sequentially) otherwise. There a couple problems with this:
The double & return type is violated if the index is even, since the constant value, 0, is returned.
It's not clear to me how to handle the situation when an even index element is used as an lvalue. E.g., v[0] = 3.0 should not be allowed in the oddvec class, but is perfectly acceptable in the vector class. We can't simply throw an error when even indexes are used, because even indexes are fine as long as the intention is as an rvalue.
How do I design the accessor function for the oddvec class, while both keeping the memory storage efficient and inheriting all the methods from the parent?
Non-working example of oddvec:
class oddvec : public vec {
public:
// Constructor.
oddvec(int n) {
len = n;
data = new double[len/2];
}
// Accessor (doesn't work!)
double & operator[](int i) const {
check_index(i);
if (i%2 == 0)
return 0;
else
return data[(i-1)/2];
}
};
Upon compilation:
main.cpp: In member function ‘double& oddvec::operator[](int) const’:
main.cpp:49:20: error: invalid initialization of non-const reference of type ‘double&’ from an rvalue of type ‘double’
return 0;
Working example using proxy classes:
I have implemented a proxy class as suggested in the answer below.
proxies.h
#ifndef PROXIES_H
#define PROXIES_H
#include <iostream>
#include <stdlib.h>
class proxy {
public:
proxy(int i, double v, double * d) {
index = i;
value = v;
data = d;
}
void operator=(double rhs) {
data[index] = rhs;
}
friend std::ostream & operator<<(std::ostream & outs, const proxy & p) {
outs << p.value;
return outs;
}
protected:
int index;
double value;
double * data;
};
class oddproxy : public proxy {
public:
oddproxy(int i, int v, double * d) : proxy(i, v, d) {}
void operator=(double rhs) {
if (index%2 == 0) {
std::cerr << "Even entries of oddvec are not assignable.\n";
exit(1);
}
data[index/2] = rhs;
}
};
#endif
vectors.h
#ifndef VECTORS_H
#define VECTORS_H
#include "proxies.h"
class vec {
public:
vec() {}
// Constructor.
vec(int n) {
len = n;
data = new double[len];
}
// Destructor.
~vec() { delete [] data; }
// Accessor.
proxy operator[](int i) const {
check_index(i);
return proxy(i, data[i], data);
}
inline int length() const { return len; }
// Other methods...
// ....
protected:
int len;
double * data;
void check_index(int i) const {
if(i < 0 || i >= len) {
std::cerr << "Bad access.\n";
exit(1);
}
}
};
class oddvec : public vec {
public:
// Constructor.
oddvec(int n) {
len = n;
data = new double[len/2];
}
// Accessor.
oddproxy operator[](int i) const {
check_index(i);
return oddproxy(i, (i%2 == 0) ? 0 : data[i/2], data);
}
};
#endif
main.cpp
#include <iostream>
#include "vectors.h"
int main () {
int N = 5;
vec V(N);
oddvec O(N);
for(int i=0; i < V.length(); i++) {
V[i] = i;
if(i%2 != 0) {
O[i] = i;
}
}
for(int i=0; i < O.length(); i++) {
std::cout << "V[" << i << "]=" << V[i] << ", "
<< "O[" << i << "]=" << O[i] << "\n";
}
O[0] = 13;
return 0;
}
output
V[0]=0, O[0]=0
V[1]=1, O[1]=1
V[2]=2, O[2]=0
V[3]=3, O[3]=3
V[4]=4, O[4]=0
Even entries of oddvec are not assignable.
You can use proxy object to do this.
simple sample code:
#include <iostream>
#include <vector>
using namespace std;
class very_odd_vector{
public:
class only_odd_proxy;
friend class only_odd_proxy;
only_odd_proxy operator [](int index);
int operator [](int index)const{return index%2==0?0:content[index/2];}
unsigned int size()const{return content.size()*2;}
private:
vector<int> content{1,3,5,7,9};
};
class very_odd_vector::only_odd_proxy{
public:
only_odd_proxy(very_odd_vector& vec,int index):vec(vec),index(index){}
operator int(){return index%2==0 ? 0 : vec.content[index/2];}
only_odd_proxy& operator =(int value){
if(index%2==0)
cout << "BAD OPERATION";//any error you want
else
vec.content[index/2] = value;
return *this;
}
private:
very_odd_vector& vec;
int index;
};
auto very_odd_vector::operator [](int index)->only_odd_proxy{return only_odd_proxy(*this,index);}
int main(){
very_odd_vector v;
cout << "reading value\n";
for(int i=0;i<v.size();++i)
cout << v[i] <<'\n';
cout << "writting value\n";
for(int i=0;i<v.size();++i){
cout << i << ':';
v[i]=10;
cout << '\n';
}
cout << "reading value\n";
for(int i=0;i<v.size();++i)
cout << v[i] <<'\n';
}
Edit for updated part of question :
I think this class will fit your need more.
//Both base and inherit class return this class
class maybe_readonly_proxy {
public:
maybe_readonly_proxy(double* data, bool readonly):readonly(readonly),data(data){}
maybe_readonly_proxy& operator=(double rhs) {
if(readonly){/*whatever error*/}
else {*data = rhs;}
return *this;
}
operator double()const{return *data;}
private:
bool readonly;
double * data;
};
You may need a variable to contain readonly (0 in this case) value, or modify the operator double() the check readonly state
Or just implement get and set method separately and do not use this proxy may be another choice.
Goal
I am working on implementing an IntegerRing, which is a structure in abstract algebra. This type of ring is an Abelian group (something that I have already implemented) under addition. Rings are equipped with two operators, + and *.
Choice of implementation
For this reason, I have decided to define IntegerGroup as class that has GroupElements that have the operators. The complete, working code for that is found below:
IntegerGroup.h
#ifndef DATAGROUP_H
#define DATAGROUP_H
#include "Array.h"
#include <iostream>
// This group is the integers mod n
// multiplication in integer group is simply integer addition modulo n
class IntegerGroup
{
public:
IntegerGroup();
IntegerGroup(int);
class GroupElement
{
int m;
IntegerGroup* group;
public:
GroupElement();
GroupElement(int, IntegerGroup*);
~GroupElement();
GroupElement operator*(const GroupElement&);
GroupElement operator*=(const GroupElement&);
bool operator==(const GroupElement&);
bool operator!=(const GroupElement&);
int val() const;
friend std::ostream& operator<<(std::ostream& o, const GroupElement& e)
{
return (o << e.m);
}
};
GroupElement identity() const;
int size() const;
friend std::ostream& operator<<(std::ostream& o, const IntegerGroup& g)
{
return (o << g.elements);
}
private:
int n;
//GroupElement * identity;
Array<GroupElement> elements;
void createNewElement(int);
};
#endif
IntegerGroup.cpp
#include "IntegerGroup.h"
#include <new>
#include <iostream>
IntegerGroup::IntegerGroup()
{
}
IntegerGroup::IntegerGroup(int n)
: n(n), elements(Array<IntegerGroup::GroupElement>(n))
{
//this is to have integers in [0,n-1]
for (int j = 0; j < n; j++)
{
this->createNewElement(j);
}
}
void IntegerGroup::createNewElement(int m)
{
// create new GroupElement
GroupElement newElement(m, this);
// store it at index m in elements
this->elements[m] = newElement;
}
IntegerGroup::GroupElement::GroupElement()
: group(0)
{
}
IntegerGroup::GroupElement::GroupElement(int m, IntegerGroup * g)
: group(g)
{
// this->m must be in [0, g->size() - 1]
this->m = m % g->size();
if (this->m < 0) this->m = g->size() + this->m;
}
IntegerGroup::GroupElement::~GroupElement()
{
if (this->group)
{
this->group = 0;
}
}
IntegerGroup::GroupElement IntegerGroup::identity() const
{
// IntegerGroup consists of all integers in [0, n-1], and identity is 0
return this->elements[0];
}
// this group is simply the integers mod n, and should be populated integers in [0,n-1]
// thus, multiplication is simply a matter of returning the element at index (a+b)%n
IntegerGroup::GroupElement IntegerGroup::GroupElement::operator*(const IntegerGroup::GroupElement& b)
{
// if the group is not defined
if (!this->group)
// we simply perform integer multiplication
return GroupElement(this->val() * b.val());
// otherwise, perform group multiplication
return GroupElement((this->val() + b.val()) % this->group->size());
}
IntegerGroup::GroupElement IntegerGroup::GroupElement::operator*=(const IntegerGroup::GroupElement& b)
{
return ((*this) = (*this) * b);
}
bool IntegerGroup::GroupElement::operator==(const IntegerGroup::GroupElement& b)
{
return this->m == b.m;
}
bool IntegerGroup::GroupElement::operator!=(const IntegerGroup::GroupElement& b)
{
return !(*this == b);
}
int IntegerGroup::GroupElement::val() const { return this->m; }
int IntegerGroup::size() const { return this->n; }
Array.cpp, Array.h are merely templated wrapper classes. The code to that is also already working. You can find the files for them on GitHub here, or you could use std::vector instead. (It just now occurred to me that right now, I could do that.)
The problem
When I tried creating IntegerRing, and compiling, I got a myriad of bizarre errors, most of which had to do with the class's own functions using private class data.
Here is my implementation thus far of IntegerRing:
IntegerRing.h
#ifndef INTEGERRING_H
#define INTEGERRING_H
#include "IntegerGroup.h"
#include "Operators.h"
class IntegerRing : public IntegerGroup
{
public:
class Element : public IntegerGroup::GroupElement
{
public:
using IntegerGroup::GroupElement;
/*Element();
Element(int);
Element(int, IntegerRing*);
~Element();*/
operator IntegerGroup::GroupElement() { return IntegerGroup::GroupElement(); }
Element(const IntegerGroup::GroupElement& el)
{
// copy everything from el into *this
this->m = el.m;
this->group = el.group;
}
/*Element operator+(const Element&);
Element operator-(const Element&);
Element operator*(const Element&);
Element operator+=(const Element&);
Element operator-=(const Element&);
Element operator*=(const Element&);*/
};
Element identity(Operators);
private:
};
#endif
IntegerRing.cpp
#include "IntegerRing.h"
#include "IntegerGroup.h"
#include "Operators.h"
/*IntegerRing::Element::Element()
{
}*/
/*IntegerRing::Element(const IntegerGroup::GroupElement& el)
{
// copy everything from el into *this
this->m = el.m;
this->group = el.group;
}
/*
IntegerRing::Element IntegerRing::Element::operator+(const IntegerRing::Element& b)
{
// IntegerRing is simply Abelian group under addition
// thus, we treat the elements like group elements first, multiply under that group, and cast to ring elements
return (IntegerRing::Element)(((IntegerGroup::GroupElement)(*this)) * ((IntegerGroup::GroupElement)b));
}
IntegerRing::Element IntegerRing::Element::operator-(const IntegerRing::Element& b)
{
int val;
// if this has a group
if (this->group)
{
// compute (this->m - b.m) % this->group->size()
val = (this->m - b.m) % this->group->size();
// if that value is negative, add this->group->size() to it
if (val < 0) val = this->group->size() + val;
}
// otherwise, val is simply the integer difference of this->m,b.m
else val = this->m - b.m;
// return element with this value
return Element(val);
}
IntegerRing::Element IntegerRing::Element::operator*(const IntegerRing::Element& b)
{
if (this->group)
return IntegerRing::Element((this->m - b.m) % this->group->size());
return IntegerRing::Element(this->m - b.m);
}
IntegerRing::Element IntegerRing::Element::operator+=(const IntegerRing::Element& b)
{
return ((*this) = (*this) + b);
}
IntegerRing::Element IntegerRing::Element::operator-=(const IntegerRing::Element& b)
{
return ((*this) = (*this) - b);
}
IntegerRing::Element IntegerRing::Element::operator*=(const IntegerRing::Element& b)
{
return ((*this) = (*this) * b);
}
*/
IntegerRing::Element IntegerRing::identity(Operators op)
{
// if op is ADDITIVE
if (op == ADDITIVE)
// return what the base version of this method would return
return (IntegerRing::Element)(((IntegerGroup::GroupElement*)this)->identity());
// multiplicative identity requested, and it is 1
return (IntegerRing::Element)this->elements[0];
}
Operators.h
#ifndef OPERATORS_H
#define OPERATORS_H
enum Operators
{
ADDITIVE, MULTIPLICATIVE
};
#endif
The compiler thinks the copy constructor for IntegerRing::Element is really a function that returns an int.
Screenshot of errors
Here is screenshot of errors:
How do I resolve all this?
The reason is that you can't access class's private fields.
Inheritance/Nested Class do not change this.(Exception is inner class can always access it's enclosing class's any member(since C++11))
For the first error in log using IntegerGroup::GroupElement; should be usingIntegerGroup::GroupElement::GroupElement; inside IntegerRing::Element, by the way, I don't see the need of this class.
Turns out that my years of not using C++ for serious OOP like this has caused me to forget things. First of which: derived classes have access to protected,public members, and not private unless you declare derived class a friend in base class.
Second: how to write copy constructors. Sadly, derived classes have access to their own inherited protected data members, not base class's. To remedy this, I just write copy constructor like this:
IntegerRing::Element::Element(const IntegerGroup::GroupElement::GroupElement& el)
: IntegerGroup::GroupElement(el)
{
}
I am struggling with adding operations of classes Natural, Rational, Complex that represent appropriate math objects. I need that to calculate polynomial in x.
All classes inherit abstract class Number. Having all coefficients in an array of Numbers I want to calculate the polynomial. To do so I need operation of multiplying by double (x is double). x gets transformed into Rational and multiplied. This works fine. My problem is how to add classes of abstract type Number?
I can't make it work. All I get is never ending recursion in Number::add(Number) (it invokes itself instead of invoking others methods for types Natural, Rational, Complex).
#include
#include
#include
#include
#include
#include
#include
using namespace std;
class Natural;class Rational;class Complex;
class Number {
public:
virtual string toString() const = 0;
virtual Number *operator*(const Rational) const = 0;
virtual Number *add(const Natural*) const = 0;
virtual Number *add(const Rational*) const = 0;
virtual Number *add(const Complex*) const = 0;
virtual Number *add(const Number *n) const {
n->add(this);
}
};
class Natural : public Number {
friend class Complex;
int n;
public:
Natural(const Natural &s) {
n = s.n;
}
Natural(int number) : n(number) {}
string toString() const {
stringstream ss;
ss << n;
return ss.str();
}
operator Rational() const;
operator Complex() const;
operator int() const {
return n;
}
Number *operator*(const Rational r) const;
Number *add(const Natural* number) const {
return new Natural(n + number->n);
}
Number *add(const Rational*) const;
Number *add(const Complex*) const;
};
class Rational : public Number {
friend class Natural;
int numerator, denominator;
void divideByGCD() {
int a = numerator, b = denominator;
//cout << a << ' ' << b << ' ';
if(a < b) {
int temp = a;
a = b;
b = temp;
}
while (b > 0) {
int r = a % b;
a = b; b = r;
//cout << r << endl;
}
numerator /= a;
denominator /= a;
//cout << a << endl;
}
public:
Rational() {}
Rational(const Rational &s) {
numerator = s.numerator;
denominator = s.denominator;
}
Rational(int n, int d) {
if(d == 0) throw new runtime_error("denominator equals 0");
if(d < 0) {
numerator = -n;
denominator = -d;
} else {
numerator = n;
denominator = d;
}
divideByGCD();
}
Rational(double d) {
int i = 0, mul = 1;
int r = d-floor(d);;
while(r!=0) {
i++; mul *= 10;
r = 10*r-floor(10*r);
}
numerator = (int)mul*d;
denominator = mul;
divideByGCD();
}
string toString() const {
stringstream ss;
ss << numerator;
if(denominator > 1) ss << '/' << denominator;
return ss.str();
}
operator const Complex() const;
operator const double() const {
return (double)numerator/denominator;
}
Number *operator*(const Rational r) const {
return new Rational(numerator*r.numerator, denominator*r.denominator);
}
Number *add(const Rational* r) const {
return new Rational(numerator*r->denominator+r->numerator*denominator, denominator*r->denominator);
}
Number *add(const Natural*) const;
Number *add(const Complex*) const;
};
class Complex : public Number {
friend class Rational;
double real, imaginary;
static const double radius = 10;
public:
Complex() {}
Complex(const Complex &s) {
real = s.real;
imaginary = s.imaginary;
}
Complex(const double r, const double im) : real(r), imaginary(im) {}
string toString() const {
stringstream ss;
ss << real;
if(imaginary != 0) ss << '+' << imaginary << 'i';
return ss.str();
}
Number *operator*(const Rational r) const;
Number *add(const Complex* c) const {
return new Complex(real + c->real, imaginary + c->imaginary);
}
Number *add(const Natural*) const;
Number *add(const Rational*) const;
};
Natural::operator Rational() const {
return Rational(n,1);
}
Natural::operator Complex() const {
return Complex(n, 0);
}
Rational::operator const Complex() const {
return Complex((double)numerator/denominator, 0);
}
Number *Natural::operator*(const Rational r) const {
return new Rational(n*r.numerator, r.denominator);
}
Number *Complex::operator*(const Rational r) const {
return new Complex(real*(double)r, imaginary*(double)r);
}
Number *Natural::add(const Rational *r) const {
if(r->denominator == 1) return new Natural(n+r->numerator);
else return new Rational(n*r->denominator,r->denominator);
}
Number *Natural::add(const Complex *c) const {
return c->add(this);
}
Number *Rational::add(const Natural *n) const {
return n->add(this);
}
Number *Rational::add(const Complex *c) const {
return new Complex(c->real+(double)*this, c->imaginary);
}
Number *Complex::add(const Natural *number) const {
return new Complex(real+number->n, imaginary);
}
Number *Complex::add(const Rational *r) const {
return r->add(this);
}
Number *poly(double x, Number *a[], unsigned int size) {
if(size == 1) return a[0];
else return a[0]->add((*poly(x, a+1, size-1))*Rational(x));
}
int main() {
cout << (Natural(5)*(Rational)2.0)->toString() << endl;
Number *coefs[] = {new Natural(5), new Natural(6)};
cout << poly(2, coefs, 2) << endl;
}
How should I fix Number::add(Number) so that while invoking add on object of type Number program itself figure out which of virtual method add to choose?
This is known as multi-dispatch. Here are some links to look at
Multiple_dispatch
best multimethods implementation
I think the problem is:
virtual Number *add(const Number *n) const {
n->add(this);
}
If you multiply a Rational by a Natural that is stored in a Number *, it can't polymorphicly upcast the Number * to a Natural *. I agree w/g-makulik in that references/values make a lot more sense here, as you are leaking memory all over the place. Remove support for Number + Number. Also, if I add a Natural and a Rational together, I get a Number * back, but what kind of number is it? I think the architecture needs a bit more thought; I might get rid of the base class pure virtual methods entirely (except maybe toString). For example:
class Number
{
public:
virtual string toString() = 0;
};
class Rational : public Number
{
string toString() {...}
// forget 'add', use operators
Rational operator+(const Rational & _rhs) const {Rational ret; ...; return ret;}
Rational & operator+=(const Rational & _rhs) const {...; return *this;}
...
}
Edit
For a quick fix, I think you just need to get rid of virtual Number *operator*(const Rational) const = 0;, and replace it with a version for each sub-class (e.x., Rational * operator*(const Natural) const)
Or, add an enumerated member variable to Number to keep track of the type:
enum Type { NATURAL, RATIONAL, ...}
Type mType;
or use RTTI, such that you can selectively choose the right add method in Number::add:
Number * add(Number * _rhs)
{
if(_rhs->mType == RATIONAL)
return this->add((Rational *)_rhs);
...
}
it looks kinda sloppy, but it will work
it looks like Visitor pattern is what I've been looking for. I wanted to have functions accept and visit in the same class. I believe my mistake was to give them the same name.
I am trying to create custom array indexed from 1 using subscript operator. Getting value works fine, but I have no clue, why assign using subscript operator doesn't work.
class CEntry {
public:
CKey key;
CValue val;
CEntry(const CKey& key, const CValue& val) {
this->key = key;
this->val = val;
}
CEntry& operator= (const CEntry& b) {
*this = b;
return *this;
};
};
...
class EntriesArray {
public:
CEntry **entries;
int length;
EntriesArray(int length) {
this->length = length;
entries = new CEntry*[length];
int i;
for (i = 0; i < length + 1; i++) {
entries[i] = NULL;
}
};
CEntry& operator[] (const int index) {
if (index < 1 || index > length) {
throw ArrayOutOfBounds();
}
return *entries[index - 1];
};
};
Constructs array this way
EntriesArray a(5);
This works
a.entries[0] = new CEntry(CKey(1), CValue(1));
cout << a[1].val.value << endl;
This doesn't work
a[1] = new CEntry(CKey(1), CValue(1));
EDIT:
Using
CEntry *operator=( CEntry *orig)
it compiles okey, but gdb stops at
No memory available to program now: unsafe to call malloc warning: Unable to restore previously selected frame
with backtrace
Program received signal EXC_BAD_ACCESS, Could not access memory.
Reason: KERN_PROTECTION_FAILURE at address: 0x00007fff5f3ffff8
0x00000001000013c8 in CEntry::operator= (this=0x0, orig=0x1001008d0) at /Users/seal/Desktop/efa du2_pokus2/efa du2_pokus2/main.cpp:20
20 /Users/seal/Desktop/efa du2_pokus2/efa du2_pokus2/main.cpp: No such file or directory.
in /Users/seal/Desktop/efa du2_pokus2/efa du2_pokus2/main.cpp
At first... This:
CEntry& operator= (const CEntry& b) {
*this = b;
return *this;
};
Shouldn't work (this should result in recursive call of operator=).
The second thing is that you're trying to assign CEntry * to CEntry, this would work if you had CEntry *operator=( CEntry *orig), but I think this is bad coding practice.
This question may be related to this one.
I tried to fix your code; I believe that this is what you were trying to do:
(tested this code on g++ 5.3.0)
#include <iostream>
#include <stdexcept>
#include <string>
// Some implementation for CKey and CValue:
typedef int CKey;
struct CValue {
int value;
CValue(int value=0) : value(value) {}
};
class CEntry {
public:
CKey key;
CValue val;
CEntry(): key(0), val(0) {}
CEntry(const CKey& key, const CValue& val): key(key), val(val) {}
CEntry& operator= (const CEntry& b) {
this->key = b.key;
this->val = b.val;
return *this;
};
};
class EntriesArray {
public:
CEntry *entries;
int length;
EntriesArray(int length) {
this->length = length;
entries = new CEntry[length];
};
CEntry& operator[] (const int index) {
if (index < 1 || index > length) {
throw std::domain_error("out of bounds!");
}
return entries[index - 1];
};
};
int main(int argc, char* argv[]) {
using namespace std;
EntriesArray a(5);
// This works
a.entries[0] = CEntry(CKey(1), CValue(1));
cout << a[1].val.value << endl;
// This doesn't work
a[1] = CEntry(CKey(2), CValue(2));
cout << a[1].val.value << endl;
}
Also you might want to use a[1] as a[1].val.value e.g.:
cout << a[1] << endl;
To do this just add to this line to cEntry:
operator int() { return val.value; }
I hope it helps.
You could try replacing
CEntry& operator[] (const int index) {
if (index < 1 || index > length) {
throw ArrayOutOfBounds();
}
return *entries[index - 1];
};
with
void Add(const int index, CEntry *pEntry) {
if (index < 1 || index > length) {
throw ArrayOutOfBounds();
}
entries[index - 1] = pEntry;
};
but since you are now storing references to objects allocated on the heap (with new) you will need a destructor ~EntriesArray() to delete them all.
Because EntriesArray::operator[] returns a CEntry &, but new CEntry returns a CEntry *.
Perhaps you want a[1] = CEntry(CKey(1), CValue(1))? (no new.)
By the way, your current definition of CEntry::operator= will lead to a stack overflow.
This
return *entries[index - 1];
dereferences a NULL pointer.
You want the pointer itself to be overwritten by a[1] = new CEntry(CKey(1), CValue(1));, not the pointed-to-value.
Try this:
class EntriesArray
{
public:
int length;
CEntry **entries;
EntriesArray( int length ) : length(length), entries(new CEntry*[length]())
{
}
// defaulted special member functions are inappropriate for this class
EntriesArray( const EntriesArray& ); // need custom copy-constructor
~EntriesArray(); // need custom destructor
EntriesArray& operator=(const EntriesArray&); // need custom assignment-operator
CEntry*& operator[] (const int index) {
if (index < 1 || index > length) {
throw ArrayOutOfBounds();
}
return entries[index - 1];
}
};
Further to my comment above:
To make it work with writing new values, you probably need something like this
(I haven't double checked for off by one or ptr vs reference stuff)
CEntry& operator[] (const int index) {
if (index < 1) {
throw ArrayOutOfBounds();
}
// Add default elements between the current end of the list and the
// non existent entry we just selected.
//
for(int i = length; i < index; i++)
{
// BUG is here.
// We don't actually know how "entries" was allocated, so we can't
// assume we can just add to it.
// We'd need to try to resize entries before coming into this loop.
// (anyone remember realloc()? ;-)
entries[i] = new CEntry();
}
return *entries[index - 1];
};