#include <iostream>
usingnamespace std;
/* Class A: pointers and operator + returns *this */
class A
{
public:
int i;
A(int _i=5){i=_i;}
A operator +(A b)
{
this->i=(this->i)+b.i;
return *this;
}
};
/* Class B: almost the same as Class A */
class B
{
public:
int i;
B(int _i=5){i=_i;}
B *operator +(B b)
{
this->i=(this->i)+b.i;
returnthis;
}
};
/* Class C: passing by reference */
class C
{
public:
int i;
C(int _i=5){i=_i;}
C &operator +(C b)
{
this->i=(this->i)+b.i;
//return this;
}
};
int main()
{
A aa(15),ab(15);
B ba(10),bb(9);
C ca(80),cb(20);
cout <<"Klase A: aa=="<<aa.i<<"\t ab=="<<ab.i<<"\t aa+ab=="; aa+ab; cout <<aa.i<<endl;
cout <<"Klase B: ba=="<<ba.i<<"\t bb=="<<bb.i<<"\t ba+bb=="; ba+bb; cout<<ba.i<<endl;
cout <<"Klase C: ca=="<<ca.i<<"\t cb=="<<cb.i<<"\t ca+cb=="; ca+cb; cout<<ca.i<<endl;
getchar();
}
Questions:
1. Which one class should I use and why?
2. When I change
1) None of them. All of them overload + incorrectly. Logically, + should not change the class.
When you do the following:
1 2
int a = 3;
int b = a + 5;
You don't expect 'a' to change. It should stay == 3.
Likewise if you do this with a class... the class should not change as a result of the addition.
The proper way to overload + would be as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13
class D
{
public:
int i;
D(int _i=5){i=_i;}
D operator + (const D& b) const
{
D temp(*this); // make a copy of this object
temp.i += b.i; // add 'b' to the temp object
return temp; // and return the temp object
// note we never change 'this'
}
};
2) I'm not sure why that would even compile, let alone crash. You can't add ca+cb.... the compiler should be giving you errors.