#define _CRT_SECURE_NO_WARNINGS 1
#include <iostream>
using namespace std;
class Base
{
public:
int A{};
void func() { cout << "Base的成员函数" << endl; }
void func(const int& m_A)
{
this->A = m_A;
cout << "Base的有参数构造函数" << endl;
}
protected:
private:
};
class Son : public Base
{
public:
int A{};
Son() {};
//void func() { cout << "Son的成员函数" << endl; }
Son(const int& m_A)
{
this->A = m_A;
cout << "Son的有参数构造函数" << endl;
}
protected:
private:
};
void test01()
{
Son s1(10);
cout << s1.A << endl; //就近原则
cout << s1.Base::A << endl; //添加作用域,访问父类中的同名成员属性
}
void test02()
{
//当子类重新定义了父类的同名函数成员,子类成员函数会隐藏掉父类中所有重载版本的同名成员
//可以利用作用域显示指定调用的函数
Son s2;
//当子类中没有与父类一样的类函数时,子类实例化的对象可以直接调用父类中的子类没有成员函数
//当子类中存在与父类的重载函数相同的函数时,子类会优先该函数,而要调用父类的重载函数,需要添加作用域
s2.func();
s2.Base::func(100);
s2.Base::func();
}
int main()
{
test01();
test02();
return 0;
}
C++中子类和父类同名成员的处理
最新推荐文章于 2022-07-26 11:07:56 发布