real,imag;
complexCls(float real = 0,float imag =0) :
real{real},imag{imag}{}
complexCls operator+(const complexCls& cls) {
return complexCls {
real+cls.real,
imag+cls.imag
};
}
};
int main() {
complexCls cls = 0 + complexCls{};
return 0;
}
why 0 can't implicitly cast to complexCls and then call + over that ?
Do you know what is *this in your operator implementation?
i don't want to mutate my object, so i didn't use that
No, you didn’t get my point. I want to direct you to the answer not give it directly to you. Since the function is a member one, there’s a ‘this’ pointer there. Try to figure out what it points to in your implementation and if that makes sense.
if i have a type T then "this" is T* or const T* did you mean what the meanning of "this" was ?
For what I know there are two ways to declare operators: - as member function - as free function (not all operators allow non-member version) And only non-member ones allow to convert the first operand as in the case you described. This also means that non-member operators can bit-by-bit slow down the compilation (as the compiler would need to consider more of them for each operator call), so declaring all operators as non-member functions is not a good idea. More about overloading operators: https://en.cppreference.com/w/cpp/language/operators More about how the call being resolved: https://en.cppreference.com/w/cpp/language/overload_resolution
"And only non-member ones allow to convert the first operand as in the case you described." i didn't understand why only non-members are allowed to cast implicity ? why the compiler can't detect the exact operator+ which called by the oher arguments we passed ? (in this case the second complex litteral complexCls{})
I'm not an expert in this question, but basically what I said above, if every operator bahaved as non-member operator, then for every operator call you would need to check all the operators of that kind ever defined in your code and in the libraries and find which can convert to the class where you defined it. It sounds pretty inefficient.
Apart from those two, you can also have a friend operator overloading inside class all of which have their specifications to prefer one over the other. Where does that bit-by-bit slow compilation come from? Haven't seen it anywhere. The problem with the OP's use case is that 0 is considered to be of the type of the struct to which this points inside the operator function. Using complexCls cls = complexCls{} + 0; would omit the problem.
I don't remember exactly but there was a talk that mentioned to not create operator overloads as free functions because of this issue
What would be the choice if the operator is binary?
Обсуждают сегодня