在编写派生类的赋值函数时,注意不要忘记对基类的数据成员重新赋值。

#include<iostream>
#include<cstring>
#include<cstdlib>
#include<cstdio>
#include<algorithm>
using namespace std;

class Base{
private:
    int x,y;

public:
    Base& operator =(const Base &other){
        x=other.x;
        y=other.y;
        printf("Base operator\n");
        return *this;
    }

    Base(){
        x=0;y=0;
        printf("base init\n");
    }
    void baseSet(int tx,int ty){
        x=tx;
        y=ty;
    }
};

class Derive:public Base{
private:
    int n,m;
public:
    Derive& operator =(const Derive &other){
        //x=other.x;
        //y=other.y;
        //这里需要调用基类的赋值函数
        
        Base::operator =(other);
        m=other.m;
        n=other.n;
        printf("Derive operator\n");
        return *this;
    }

    Derive(){
        n=1;m=1;
        printf("Derive init\n");
    }

    void DeriveSet(int tn,int tm){
        n=tn;
        m=tm;
    }
};

int main(){
    Derive a=Derive();
    Derive b=Derive();
    b.baseSet(9,9);
    b.DeriveSet(8,8);
    
    a=b;
}

参考:高质量C++C 编程指南