6.3w+
社区成员
#include <iostream>
using namespace std;
class student{
static int count;
int studentno;
public:
student ()
{
count++;
studentno=count;
}
void print()
{
cout <<"student" <<studentno
<<"count=" <<count <<endl;
}
~student() {}
};
int student::count=0;
int main()
{
student student1;
student1.print();
cout <<" \n";
student student2;
student1.print();
student2.print();
cout <<" \n";
student student3;
student1.print();
student2.print();
student3.print();
cout <<" \n";
student student4; //每次创建一个类,那么他的就自己调用一次构造函数,但
//是构造函数里面的studentno是用count初始化的,而
//你要知道,static成员对一个类的所有对象而言都是共有的
//所以你每次构造一个对象,那么count就++了一次,之前的student1
//的count和之后的count都公用
/*
至于你问为什么不是:
student4 count=4
student4 count=4
student4 count=4
student4 count=4
而是student1 count=4
student2 count=4
student3 count=4
student4 count=4
只能说明你的书读的害不够,student后面的1234是由studentno决定的,
这个东西不是static的,不是共有的,在对象构造之初就已经确定了的,同志!!
*/
student1.print();
student2.print();
student3.print();
student4.print(); //你在这里每次都是调用的
return 0;
}
#include <iostream.h>
class student{
static int count;
int student no;
pbulic:
{
count++;
studentno=count;
}