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 @   double64  阅读(4)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示