简体   繁体   中英

Assignment operator overload

I have class that has assignment to string operator.

class turbo
    {
public:
    operator string   (void) {printf("assignment to string operator\n");return "bla2";}
    };

Assignment operation works just fine:

turbo t;
string s;
s=t;

And I have "assignment to string operator" in output.

Then I decided to make another assignment operator to turbo

class turbo
    {
public:
    operator string   (void) {printf("assignment to string operator\n");return "bla";}
    operator turbo   (void) {printf("assignment to turbo operator\n");return *this;}
    };

But code below does not calls turbo assignment operator.

turbo t;
turbo tt ;
tt=t;

Why?

I know that I can overload = operator, but I expect operator turbo work also since string one is operating.

You are not overloading assignment operators, but conversion operators. So they are called when conversion takes place.

See c++: cast operator vs. assign operator vs. conversion constructor priority

The implicitly-declared copy assignment operator of a class takes a single parameter of type X const& (here turbo const& ). Since your RHS operand is already of type turbo , there is no need to call the conversion function.

Indeed, a conversion function to the same type is never called implicitly; it can only be called explicitly (as turbo::operator turbo() ) or possibly via a virtual conversion function in a base class. This is discussed in [class.conv.fct] :

1 - [...] A conversion function is never used to convert a (possibly cv-qualified) object to the (possibly cv-qualified) same object type (or a reference to it), to a (possibly cv-qualified) base class of that type (or a reference to it), or to (possibly cv-qualified) void. [...]

See Under what circumstances would a type's conversion operator to itself be invoked?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM