简体   繁体   中英

C++ assignment operator resolving

Consider the following code:

struct A
{
    void foo( const char * ) { cout << __PRETTY_FUNCTION__ << endl; }
    A & operator = ( const A &  ) { cout << __PRETTY_FUNCTION__ << endl; return * this; }
};


struct B : public A
{
    void foo( const char * ) { cout << __PRETTY_FUNCTION__ << endl; }
    A & operator = ( const A & other ) { cout << __PRETTY_FUNCTION__ << endl; return * this; }
};

Then when we call this members:

B b;

b.foo( "hehe" );
b = b;

Will be printed:

void B::foo( const char *)
A& A::operator=(const A&)

Question: why B::foo hides A::foo, but B::operator= doesn't?

What you see is not a hiding problem at all. You did not create an assignment operator to assign B into B, therefore the compiler created one for you. The one created by the compiler is calling assignment operator of A.

Therefore, if your question "Question: why B::foo hides A::foo, but B::operator= doesn't?" should be read "How is operator= different from an ordinary function", the difference is compiler will provide one for you if you do not write your own.

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