首页 > 代码库 > c++中基类和子类的成员变量同名

c++中基类和子类的成员变量同名

#include <iostream>

using namespace std;

class Base{
    public:
        Base(void):m_i(0){}
        Base(int i):m_i(i){}
        int m_i;
};                                                                                                                                     

class Derived:public Base{
    public:
        Derived(void):m_i(0){}
        Derived(int i,int j):Base(i),m_i(j){}
        Derived(const Derived& that):
            m_i(that.m_i),Base(that){}
        Derived& operator=(const Derived& that){
            if(&that != this){
                m_i = that.m_i;
                Base::operator=(that);
                //基类Base看似没有Base& operator=(const Base& that)
                //这个赋值拷贝函数,但是系统会为其添加一个
            }
        }
        int m_i;//覆盖了基类Base总的成员变量m_i.
};
int main(void){
    Derived d1(100,200);
    Derived d2(d1);
    //通过这样来访问基类中的同名成员变量.
    cout << d1.Base::m_i << ‘ ‘ <<d1.m_i << endl;//100,200
    cout << d2.Base::m_i << ‘ ‘ <<d2.m_i << endl;//100,200
    Derived d3;
    d3 = d1;
    cout << d3.Base::m_i << ‘ ‘ <<d3.m_i << endl;//100,200
    }


本文出自 “12208412” 博客,请务必保留此出处http://12218412.blog.51cto.com/12208412/1867463

c++中基类和子类的成员变量同名