首页 > 代码库 > 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++中基类和子类的成员变量同名
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。