以下模式确定/安全吗?或者有任何缺点吗?(我也将它用于相等运算符)
Derived& operator=(const Derived& rhs)
{
static_cast<Base&>(*this) = rhs;
// ... copy member variables of Derived
return *this;
}
Run Code Online (Sandbox Code Playgroud)
Moo*_*ice 47
这很好,但是通过名称调用基类是更加可读的恕我直言:
Base::operator = (rhs);
Run Code Online (Sandbox Code Playgroud)
peo*_*oro 13
是的,这很安全.
执行相同操作的不同语法可能是:
Base::operator=( rhs );
Run Code Online (Sandbox Code Playgroud)
这样使用更好
Base::operator=(rhs);
Run Code Online (Sandbox Code Playgroud)
因为如果您的基类具有纯虚方法,则不允许使用 static_cast。
class Base {
// Attribute
public:
virtual void f() = 0;
protected:
Base& operator(const Base&);
}
class Derived {
public:
virtual void f() {};
Derived& operator=(const Derived& src) {
Base::operator=(src); // work
static_cast<Base&>(*this) = src; // didn't work
}
}
Run Code Online (Sandbox Code Playgroud)