C++ 调用基类的运算符...安全吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4734846/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 16:18:19  来源:igfitidea点击:

calling operators of base class... safe?

c++operators

提问by smerlin

Is following pattern ok/safe ? Or are there any shortcomings ? (I also use it for equality operators)

以下模式可以/安全吗?或者有什么缺点?(我也将它用于相等运算符)

Derived& operator=(const Derived& rhs)
{
    static_cast<Base&>(*this) = rhs;
    // ... copy member variables of Derived
    return *this;
}

回答by Moo-Juice

This is fine, but it's a lot more readable IMHO to call the base-class by name:

这很好,但恕我直言,按名称调用基类更具可读性:

Base::operator = (rhs);

回答by peoro

Yes, it's safe.

是的,它很安全。

A different syntax to do the same thing could be:

做同样事情的不同语法可能是:

Base::operator=( rhs );

回答by olive007

That's better to use

这样使用更好

Base::operator=(rhs);

because if your base class have a pure virtual method the static_cast is not allowed.

因为如果您的基类具有纯虚方法,则不允许使用 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
        }
}