子类可以继承父类的静态变量,如果子类也定义了同名的静态变量或者非静态变量,那么在使用父类的静态变量时需要用类::静态变量
。
同名静态变量
#include <iostream>
using namespace std;
class Single{
};
class stest{
public:
static int s;
};
int stest::s=10;
class schld:public stest{
public:
// schld():s(12){}
static int s; // 生明和父类同名的静态成员变量
};
int schld::s=20; // 初始化定义子类的静态成员变量
void test(){
schld sc;
sc.stest::s++;
cout<<stest::s<<endl;
cout<<sc.s<<endl; // 如果子类中声明了两个同名的静态变量,两个静态变量互不干扰,否则,子类使用父类的静态变量
sc.s++;
cout<<stest::s<<endl;
cout<<sc.s<<endl;
}
int main(){
test();
return 0;
}
非同名静态变量
#include <iostream>
using namespace std;
class Single{
};
class stest{
public:
static int s;
};
int stest::s=10;
class schld:public stest{
public:
schld():s(12){}
int s;
};
void test(){
schld sc;
cout<<sc.stest::s++<<endl;;
cout<<stest::s<<endl;;
cout<<sc.s<<endl;
}
int main(){
test();
return 0;
}