//1、子类中的同名成员可以直接访问
//2、父类中的同名成员需要加上作用域
//3、子类中的同名成员会隐藏掉父类中的所用同名成员函数,加作用域可以访问
#include<iostream>
using namespace std;
class Base {
public:
int m_a;
Base() {
m_a = 100;
}
void func() {
cout << "Base的func函数调用" << endl;
}
void func(int a) {
cout << "Base中的同名函数func调用" << endl;
}
};
class son :public Base {
public:
son() {
m_a = 200;
}
int m_a;
void func() {
cout << "son的func函数调用" << endl;
}
};
void test() {
son s;
s.func();
s.Base::func();
s.Base::func(10);
cout <<"son下的m_a="<< s.m_a << endl;
cout << "Base下的m_a=" << s.Base::m_a << endl;
}
int main() {
test();
return 0;
}
文章讲述了在C++中,子类对父类同名成员的处理方式。子类会隐藏父类的同名成员函数,但可以通过作用域解析运算符来访问。示例代码展示了如何在子类中调用父类的同名成员函数和数据成员。
418

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



