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
 
                    
                     
                    
                 
                    
                 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号