So when "redefining" operator+() inside the class you need to specify the type of the argument? |
Yes, you specify the type of the variable on the right hand side of the "+" operator. You could also define
CVector::operator+(double d);
This would let you do something like
vec1 = vec2 + 8.4;
If that is the case, I don't understand why you need to declare it constant |
Since the + operator doesn't modify the right hand side object, it's good to define it that way so you can call it with a const object. It can also help the optimizer. In fact, you should define the operator as const also:
CVector operator + (const CVector&) const;
That way you'll be able to do
vec1 + vec2 + vec3;
and why you have to include the & at the end
This is for efficiency. If the method was operator+(const CVector param) then every time you called +, it would make a copy of the vector, use it as the param, and then destroy it. This isn't too big a deal with CVector, but imagine if it had 1000 elements instead: all that copying would be a performance killer.
Now some points about style, which you should feel free to ignore. When overriding a binary operator, I universally call the parameter "rhs" for "right hand side." It helps me remember that this is the right hand side of the + operation.
Also, if I need to write operator+(), I usually write operator+=() instead. Then you can get operator+() practically for free:
1 2 3 4 5
|
MyClass operator +(const MyClass &rhs) const {
MyClass result(*this);
result += rhs;
return result;
}
|
Two useful operations for the price of one!