下面是主干程序:(定义了一组继承,父类中定义了一个名字相同的静态有参构造函数和静态无参构造函数,子类中重写了从父类中继承来的同名函数。
后面会给出三个test测试块,分别说明不同的问题。
#include<iostream>
using namespace std;
class father {
public:
static void fun() {
cout << "父类的静态无参函数被调用" << endl;
}
static void fun(int a) {
cout << "父类的静态有参函数被调用" << endl;
}
static int m_a;
};
int father::m_a = 100;
class son :public father {
public:
static void fun() {
cout << "子类的静态无参函数被调用" << endl;
}
static int m_a;
};
int son:: m_a = 200;
测试块1://这一块内容和之前的非静态调用一样,不再赘述
//通过对象调用的方式调用
void test01() {
son s;
s.fun();
}
测试块2://指针访问,这部分也和之前的非虚函数一样。
void test02() {
cout << "通过父类指针来访问子类对象" << endl;
son s;
father* f1 = new son(s);
f1->fun(5);
f1->fun();
cout << f1->m_a << endl;
delete f1;
}
测试块3://通过类名直接访问静态成员(这是静态成员独有的地方)
void test03() {
cout << "直接通过类名访问静态数据成员: " << endl;
cout << "son类中的 m_a = " << son::m_a << endl;
cout << "父类中的m_a = " << son::father::m_a << endl;//第一个::表示通过类目来访问,第二个::表示作用域符
cout << " " << endl;
cout << "直接通过类名访问静态函数成员: " << endl;
father::fun();
father::fun(5);
son::fun();
}