# 静态数据成员的难点

code145 2008-03-07 06:10:21
#include<iostream.h>
class student{
static int count;
int student no;
pbulic:
{
count++;
studentno=count;
}
void print()
{
cout<<"student"<<studentno<<"";
cout<<"cout="<<cout<<endl;
}
};
int student::count=0;
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;
student1.print();
student2.print();
student3.print();
student4.print();
return 0;
}

student1 count=1

student1 count=2
student2 count=2

student1 count=3
student2 count=3
student3 count=3

student1 count=4
student2 count=4
student3 count=4
student4 count=4

...全文
98 7 打赏 收藏 举报

7 条回复

mhtcc520 2008-03-08
• 打赏
• 举报

IT_lau 2008-03-08
• 打赏
• 举报

count在不停的变啊，到第四步成4了都，，，，

• 打赏
• 举报

``````
#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

student2 count=4
student3 count=4
student4 count=4

*/
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;
} ``````

public都不对，你怎么得到你的结果啊？

code145 2008-03-08
• 打赏
• 举报

student4 count=4
student4 count=4
student4 count=4
student4 count=4 才对啊!

student2 count=4
student3 count=4
student4 count=4

ttkk_2007 2008-03-07
• 打赏
• 举报

hityct1 2008-03-07
• 打赏
• 举报

6.3w+

C++ 语言相关问题讨论，技术干货分享，前沿动态等
c++ 技术论坛（原bbs）

2008-03-07 06:10

1. 请不要发布与C++技术无关的贴子
2. 请不要发布与技术无关的招聘、广告的帖子
3. 请尽可能的描述清楚你的问题，如果涉及到代码请尽可能的格式化一下