C++ 派生类赋值运算符应显式调用

struct Base
{
    double x{ 111.1 };
};

struct Derive :public Base
{
    double y{ 222.2 };
    Derive& operator=(const Derive& obj)
    {
        if (&obj == this)
        {
            return *this;
        }
        Base::operator=(obj); // 显示调用基类operator=
        // 酌情处理自赋值的问题
        y = obj.y;
        return *this;
    }
};


int main()
{
    Derive d;
    d.x = 1.1;
    d.y = 2.2;

    Derive d1;
    d1.x = 3.3;
    d1.y = 5.5;

    d = d1;
    cout << d.x << '\n'; // 若不显示调用基类operator=,还是1.1
    cout << d.y << '\n'; // 

    system("pause");
    return EXIT_SUCCESS;
}

输出:

3.3
5.5




参考:《C++ Primer》 P555

posted @ 2024-09-14 23:10  double64  阅读(12)  评论(0)    收藏  举报