不管这个类创建了多少个对象,而其静态成员只有一个拷贝(副本),这个拷贝被所有属于这个类的对象共享。
static 数据类型 静态数据成员名;
using namespace std;
class KMyClass
{
private:
static int i; //声明i为私有静态数据成员
public:
static int j; //声明j为公有静态数据成员
int Geti()
{
return i;
}
int Getj()
{
return j;
}
};
int KMyClass::i = 0; //静态数据成员初始化
int KMyClass::j = 0;
int main()
{
KMyClass::j = 200; //公有静态数据成员可以在对象定义之前被访问
cout<<"KMyClass::j = "<<KMyClass::j<<endl;
KMyClass ob1, ob2;
cout<<"ob1.i = "<<ob1.Geti()<<endl;
cout<<"ob1.j = "<<ob1.Getj()<<endl;
cout<<"ob2.i = "<<ob2.Geti()<<endl;
cout<<"ob2.j = "<<ob2.Getj()<<endl;
ob1.j = 300; //公有静态数据成员也可通过对象进行访问
cout<<"ob1.j = "<<ob1.Getj()<<endl; //静态数据成员是对象的共享数据项
cout<<"ob2.j = "<<ob2.Getj()<<endl;
return 0;
}
using namespace std;
class Small_Cat
{
private:
double weight;
static double total_weight;
static double total_number;
public:
Small_Cat(double w)
{
weight = w;
total_weight += w;
total_number++;
}
void Display()
{
cout<<"The small_cat weights "<<weight<<" pounds\n";
}
static void Total_Disp() //静态成员函数,显示小猫的只数和总重量
{
cout<<total_number<<" small_cat total weight "<<total_weight<<" pounds"<<endl;
}
};
double Small_Cat::total_weight = 0;
double Small_Cat::total_number = 0;
int main()
{
Small_Cat w1(1.8), w2(1.6), w3(1.5);
w1.Display();
w1.Total_Disp();
w2.Display();
w2.Total_Disp();
w3.Display();
w3.Total_Disp();
Small_Cat::Total_Disp();
return 0;
}
The small_cat weights 1.8 pounds
2万+




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



