继承中静态成员的处理
类似非静态成员函数处理
如果想访问父类中的成员,加作用域即可
静态成员函数和非静态成员函数的共同点:
1. 他们都可以被继承到派生类中。
2. 如果重新定义一个静态成员函数,所有在基类中的其他重载函数会被隐藏。
3. 如果我们改变基类中一个函数的特征,所有使用该函数名的基类版本都会被隐藏。
静态成员函数不能是虚函数(virtual function)
main.cpp
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
class Base
{
public:
static void func()
{
cout << "base fun()" << endl;
}
static void func(int a)
{
cout << "base fun(int)" << endl;
}
static int m_A;
};
int Base::m_A = 10;
class Son :public Base
{
public:
static void func()
{
cout << "son fun()" << endl;
}
static int m_A;
};
int Son::m_A = 20;
//静态成员属性 子类可以继承下来
void test01()
{
cout << "Son::m_A====" << Son::m_A << endl;
//访问父类的m_A
cout << "Base::m_A====" << Base::m_A << endl;
Son::func();
//访问 父类中同名的函数
Son::Base::func(10);
}
int main(){
test01();
system("pause");
return EXIT_SUCCESS;
}
输出
Son::m_A====20
Base::m_A====10
son fun()
base fun(int)
本文探讨了在C++中,静态成员函数和属性在继承中的行为。详细讲解了如何在派生类中访问和重定义基类的静态成员,以及它们与非静态成员的区别。通过实例代码展示了静态成员函数的重载和隐藏机制。
684

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



