If I overload an operator, such as <<, what will be the associativity?
For my tests I used a simple class, defined as:
class Complex {
Complex(float re = 0, float im = 0) {
real = re;
imag = im;
}
const Complex & operator=(const Complex& c) {
if (this != &c) {
real = c.real;
imag = c.imag;
}
return *this;
}
ostream& operator << (ostream& out, const Complex& z) {
z.show(out);
return out;
...
}
};
My tests have shown that operator<<(ostream& out, const Complex& z) is left-to-right associative, as is usual for the << operator. Also, operator=(const Complex &c) is right-to-left associative, as is normal for the = operator.
This leads me to believe that the associativity of my overloaded operators is based on the associativity of the default operators (or that the actual symbols used specify associativity, and not the function itself). My lecturer however, tells me that the associativity is decided by the compiler based on the return types of the overloaded operators.
Which is correct?
(or, if I've explained it poorly, just answer: How is the associativity for overloaded operators determined?)
Question
Bukkfrig
If I overload an operator, such as <<, what will be the associativity?
For my tests I used a simple class, defined as:
My tests have shown that operator<<(ostream& out, const Complex& z) is left-to-right associative, as is usual for the << operator. Also, operator=(const Complex &c) is right-to-left associative, as is normal for the = operator.
This leads me to believe that the associativity of my overloaded operators is based on the associativity of the default operators (or that the actual symbols used specify associativity, and not the function itself). My lecturer however, tells me that the associativity is decided by the compiler based on the return types of the overloaded operators.
Which is correct?
(or, if I've explained it poorly, just answer: How is the associativity for overloaded operators determined?)
Thanks for your help.
Link to comment
Share on other sites
3 answers to this question
Recommended Posts