同名成员函数
#include <iostream>
using namespace std;
class A
{
public:
int a;
int b;
public:
void get()
{
cout<<"b "<<b<<endl;
}
void print()
{
cout<<"AAAAA "<<endl;
}
protected:
private:
};
class B : public A
{
public:
int b;
int c;
public:
void get_child()
{
cout<<"b "<<b<<endl;
}
void print()
{
cout<<"BBBB "<<endl;
}
protected:
private:
};
int main()
{
B b1;
b1.print();
b1.A::print();
b1.B::print(); //默认情况
return 0;
}
同名成员变量
#include <iostream>
using namespace std;
class A
{
public:
int a;
int b;
public:
void get()
{
cout<<"b "<<b<<endl;
}
void print()
{
cout<<"AAAAA "<<endl;
}
protected:
private:
};
class B : public A
{
public:
int b;
int c;
public:
void get_child()
{
cout<<"b "<<b<<endl;
}
void print()
{
cout<<"BBBB "<<endl;
}
protected:
private:
};
//同名成员变量
int main()
{
B b1;
b1.b = 1; //修改的是子类的b
b1.get_child();
b1.get();
b1.A::b = 100; //修改父类的b
b1.B::b = 200; //修改子类的b 默认情况是B
b1.get();
b1.get_child();
cout<<"hello..."<<endl;
return 0;
}
本文通过两个示例介绍了 C++ 中基类和派生类成员函数及成员变量同名时的处理方式。展示了如何区分调用基类与派生类中的同名成员,并演示了对同名成员变量进行操作的具体方法。
671

被折叠的 条评论
为什么被折叠?



