I have tried to overload the "+" operator for my class:
Vector operator+( const Vector& a, const Vector& b );
However,it tells me:
vector.h(12): error C2804: binary 'operator +' has too many parameters
I really don't get it. Please help me
I have tried to overload the "+" operator for my class:
Vector operator+( const Vector& a, const Vector& b );
However,it tells me:
vector.h(12): error C2804: binary 'operator +' has too many parameters
I really don't get it. Please help me
If you define the operator in the class, it should only receive 1 argument.
class Vector {
...
Vector operator+ (const Vector& other) const {
Vector res = *this;
res += other;
return res;
}
...
};
The 2 argument version is used if you define it outside of the class definition.
class Vector {
...
};
Vector operator+ (const Vector& first, const Vector& second) {
Vector res = first;
res += second;
return res;
}
I guess you are placing the code inside the class, if that is the case, you only need to give 1 parameter (the other object), because by default the this object is on the left hand side.
I believe you have declared this as member method of class Vector. In that case it should take only one parameter as the object on which this operator is called is implictly available through this pointer. Alternalitevly, you can declare the function as a friend of class Vector and take two parameters to it.
This is because the Vector on the left of the operator and the one on the right are not the first and second arguments. The one before the + is actually this, which is automatically supplied as a Vector *. You only need one argument, and that's for the Vector to the right of the + operator.
This would be correct:
Vector operator+( const Vector& b );
You can access the left Vector by:
(* this)
... and the right Vector by:
b
When overloading + operator you can only have one parameter. The other parameter is "this"
The concrete error has been answered in a few answers already. Single parameter for the member method, two parameters for the free function version. But no hint into what path you should follow: should you remove the first parameter or else make it a free function?
The common idiom is that if you provide operator+ you might also want to provide operator+=, and if you are providing both, you can implement the first in terms of the latter. Implement operator+= as a member function (with full access to all the state) and operator+ as a free function that only needs to use the public operator+=:
class MyClass {
public:
MyClass& operator+=( MyClass const & rhs );
};
MyClass operator+( MyClass lhs, MyClass const & rhs ) {
return lhs+=rhs;
}
This way you have a single implementation for the operation, and you can provide both interfaces (a + b or a += b) so your interface is richer at almost no cost.