简体   繁体   中英

assignment operator in c++

let's assume I have some class A and derived from it B: I want to write operator= for B (let's assume that I have operator= in my A class) right way to do this:

B& B::operator=(const B& rhs)
{
if(this == &rhs) return *this;
((A&) *this) = rhs; //<-question
//some other options
return *this
}

what is the difference if I write

((A) *this) = rhs;

thanks in advance

Your second code would copy just the A part (slicing) of *this into a temporary variable, assign it, and throw it away. Not very helpful.

I would instead write that line as:

A::operator=(rhs);

which makes it very clear that it is invoking the base class version.

Cast-and-assign could be better in a template situation where you don't actually know what your base class is, and whether it has an operator= member or friend or what.

In that case:

A* basethis = this;
*basethis = rhs;

is easier to read and understand.

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