zoukankan      html  css  js  c++  java
  • 继承中赋值函数的注意点

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

    #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
    ");
            return *this;
        }
    
        Base(){
            x=0;y=0;
            printf("base init
    ");
        }
        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
    ");
            return *this;
        }
    
        Derive(){
            n=1;m=1;
            printf("Derive init
    ");
        }
    
        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 编程指南

  • 相关阅读:
    day2-元组 列表-赋值和深浅拷贝
    day1-bytes类型 三元运算 进制
    DAY02
    DAY02
    Python格式化、显示颜色
    DAY02
    DAY02
    DAY02
    DAY02
    DAY02
  • 原文地址:https://www.cnblogs.com/huhuuu/p/3460406.html
Copyright © 2011-2022 走看看