I understand that in C++ you can overload an operator like a function. And as common with functions in C++, you have to specify a return value:
struct A {
int operator +();
};
Here I’ve overloaded operator+ as a function that returns an int. But I find that when I overload a type while giving it a return value, I get error: return type specified for 'operator int'.
struct A {
void operator int() {} // error
};
But if I take away the return value it works fine.
struct A {
operator int() {} // pass
};
Does the error mean that by my use of int before the function parameters, that I’m creating a function that returns an int. Or is this some mistake? What if I want the function to not return a value? Can someone please explain why I’m getting this error? Thanks.
By definition,
operator int()returns anint. It will be called in contexts where an object of typeAneeds to be converted toint. That’s quite different from the first code snippet, where the operator isoperator+(); you can define it to return pretty much anything you like.