继承中的同名成员变量处理方法
1、当子类成员变量与父类成员变量同名时
2、子类依然从父类继承同名成员
3、在子类中通过作用域分辨符::进行同名成员区分(在派生类中使用基类的同名成员,显式地使用类名限定符)
4、同名成员存储在内存中的不同位置
总结:同名成员变量和成员函数通过作用域分辨符进行区分
#include<iostream>
using namespace std;
class A
{
public:
int a;
int b;
public:
void get()
{
cout<<"A的b: "<<b<<endl;
}
void print()
{
cout<<"父类的AAAA"<<endl;
}
protected:
private:
};
class B:public A
{
public:
int c;
int b;
public:
void get_child()
{
cout<<"B的b: "<<b<<endl;
}
void print()
{
cout<<"子类的BBBB"<<endl;
}
protected:
private:
};
//同名成员变量
int main01()
{
B b1;
b1.b = 1;//这样写默认修改的是子类的B
b1.get_child();
b1.A::b = 100;//想要修改父类的b要这样才对
b1.get();
b1.B::b = 300;//
b1.get_child();
system("pause");
return 0;
}
//同名成员函数
int main()
{
B b1;
b1.print();//默认的调用子类的b
b1.A::print();
b1.B::print();
system("pause");
return 0;
}