学习本章之前需要 复习静态成员函数的知识点。
静态成员函数和非静态成员函数出现同名,处理方式一致
1:访问子类同名成员 直接访问即可。
2:访问父类同名成员 需要加作用域。
示例:
#include<iostream>
using namespace std;
class Base
{
public:
static int m_a;
static void show()
{
cout<<"Base 函数的调用"<<endl;
}
static void show(int a)
{
cout<<"Base->函数的调用"<<endl;
}
};
int Base::m_a=100;
class son:public Base
{
public:
static int m_a;
static void show()
{
cout<<"son 函数的调用"<<endl;
}
};
int son::m_a=200;
//同名静态成员属性
void test()
{
son p;
cout<<"通过对象进行调用"<<endl;
cout<<"son m_a="<<p.m_a<<endl;
cout<<"Base m_a="<<p.Base::m_a<<endl;
cout<<"通过类名进行调用"<<endl;
cout<<"son ->m_a="<<son::m_a<<endl;
//第一个::代表我要通过类名访问一个数据 第二个::代表访问父类作用域下访问m_a;
cout<<"Base->m_a="<<son::Base::m_a<<endl;
}
//同名静态成员函数
void test0()
{
son p;
cout<<"通过对象进行同名静态成员函数调用"<<endl;
p.show();
p.Base::show();
cout<<"通过类 进行同名静态成员函数调用"<<endl;
son::show();
son::Base::show();
//如果子类中出现父类中同名静态成员函数,那么会隐藏父类中所有同名静态成员函数。
son::Base::show(100);
}
int main()
{
test();
test0();
return 0;
}
网址:https://www.bilibili.com/video/BV1et411b73Z?p=132&spm_id_from=pageDriver