让我们假设我有一些A类并从中派生出来B:我想operator=为B 编写(让我们假设我有operator=我的A类)正确的方法来做到这一点:
B& B::operator=(const B& rhs)
{
if(this == &rhs) return *this;
((A&) *this) = rhs; //<-question
//some other options
return *this
}
Run Code Online (Sandbox Code Playgroud)
如果我写的话有什么不同
((A) *this) = rhs;
Run Code Online (Sandbox Code Playgroud)
提前致谢
你的第二个代码只会将A部分(切片)复制*this到一个临时变量中,分配它,并将其丢弃.不是很有帮助.
我会把那行写成:
A::operator=(rhs);
Run Code Online (Sandbox Code Playgroud)
这很清楚它是在调用基类版本.
在模板情况下,转换和分配可能会更好,在这种情况下,您实际上不知道您的基类是什么,以及它是否有operator=成员或朋友或什么.
在这种情况下:
A* basethis = this;
*basethis = rhs;
Run Code Online (Sandbox Code Playgroud)
更容易阅读和理解.