+ 1
Binary operators with objects
I 've got this problem: I 'm writing a c++ class and using operator overloading I saw that in a case like the "+" case I can 't take the object as the second argument, only as the first. How can I fix this? P. S. : I 'm sure it 's possible to fix that because using the <string> library it works and returns the sum of a char* variable and a std::string object.
4 Antworten
0
You have to declare the function out of the class declaration, like this:
class Example {
public:
int a;
test(int a = 0) {
this->a = a;
}
void operator+(Example a) {
cout << this->a + a.a << endl;
}
void operator+(int a) {
cout << this->a + a << endl;
}
};
void operator+(int a, Example b) {
cout << a + b.a << endl;
}
int main {
Example a = 3;
a + a;
a + 4;
5 + a;
}
Output:
6
7
8
+ 2
Alright, sorry for the misunderstanding. :)
+ 1
Why do you need to pass 2 arguments to the + operator?
The first object is called this, while the argument you pass to the operator is the 2nd object.
For example:
( Just assume Object has some member variable called a )
...
Object operator+( const Object& other )
{
Object tmp = *this;
tmp.a += other.a;
return tmp;
}
...
Object a, b;
Object c = a + b;
- 1
I meant when I use the operator to perform an operation between a non-object type as first argument and an object type as second argument, so I can 't use the this keyword. At least I found my answer. Thanks Dennis.