派生关系中的静态成员(P182)
/*
如果基类中的成员是静态的,则在其派生类中,被继承的成员也是静态的,即其静态属性随静态成员被继承。
如果基类的静态成员是公有的或是保护的,则它们被其派生类继承为派生类的静态成员。访问这些成员时,通常用“<类名>::<成员名>”的方式引用或调用。无论有多少个对象被创建,这些成员都只有一个拷贝,它为基类和派生类的所有对象所共享。
*/
#include<iostream>
using namespace std;
class Base //基类
{
private:
float x;
public:
static int staV;
Base()
{
staV++;
}
};
int Base::staV=0;
class Derived:public Base //派生类
{
private:
float y;
public:
Derived()
{
staV++;
}
};
int main()
{
Base a;
cout<<a.staV<<endl; //输出1
Derived d;
cout<<d.staV<<endl; //输出3
return 0;
}
#include<iostream>
using namespace std;
class Base //基类
{
private:
float x;
public:
static int staV;
Base()
{
staV++;
}
};
int Base::staV=0;
class Derived:public Base //派生类
{
private:
float y;
public:
Derived()
{
staV++;
}
};
int main()
{
Base a;
cout<<a.staV<<endl; //输出1
Derived d;
cout<<d.staV<<endl; //输出3
return 0;
}

浙公网安备 33010602011771号