以下模式是否正常/安全?或者有任何缺点吗? (我也将它用于相等运算符)
Derived& operator=(const Derived& rhs)
{
static_cast<Base&>(*this) = rhs;
// ... copy member variables of Derived
return *this;
}
答案 0 :(得分:47)
这很好,但是通过名称调用基类是更加可读的恕我直言:
Base::operator = (rhs);
答案 1 :(得分:13)
是的,这很安全。
执行相同操作的不同语法可能是:
Base::operator=( rhs );
答案 2 :(得分:2)
最好使用
Base::operator=(rhs);
因为如果您的基类具有纯虚方法,则不允许使用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
}
}