让我们假设我有一些类 A 并从它派生 B:
我想为 B 编写 operator=
(假设我的 A 类中有 operator=
)
正确的做法:
B& B::operator=(const B& rhs)
{
if(this == &rhs) return *this;
((A&) *this) = rhs; //<-question
//some other options
return *this
}
如果我写有什么区别
((A) *this) = rhs;
提前致谢
最佳答案
您的第二个代码将只复制 *this
的 A
部分(切片)到一个临时变量中,分配它,然后丢弃它。不是很有帮助。
我会将该行写成:
A::operator=(rhs);
这很清楚它正在调用基类版本。
在您实际上不知道基类是什么,以及它是否有一个 operator=
成员或友元之类的模板情况下,强制转换和赋值可能会更好。
在那种情况下:
A* basethis = this;
*basethis = rhs;
更易于阅读和理解。
关于c++ - C++中的赋值运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3847916/