静态数据成员:
直接上例程分析:
#include <iostream>
using namespace std;
class Student{
private:
string name;
int n=0;
public:
void set(string str){
static int number = 0;
name = str;
n=++number;
}
void print(){
cout << name.c_str() << "-> studnets are " << n<< " numbers\n" << endl;
}
};
void fn(){
Student s1;
s1.set("Jenny");
Student s2;
s2.set("Randy");
s1.print();
}
int main()
{
Student s;
s.set("Smith");
fn();
s.print();
return 0;
}
运行结果:
看到结果发现:输出的结果都是错误的。这是不同的对象有不同的数据成员n值所致。
改正程序:
#include <iostream>
using namespace std;
class Student{
private:
string name;
static int number;
public:
void set(string str){
name = str;
++number;
}
void print(){
cout << name.c_str() << "-> studnets are " << number << " numbers\n" << endl;
}
};
int Student::number = 0;
void fn(){
Student s1;
s1.set("Jenny");
Student s2;
s2.set("Randy");
s1.print();
}
int main()
{
Student s;
s.set("Smith");
fn();
s.print();
return 0;
}
改进后,static int number的结果存放在专属于Student类名空间的全局数据区中,不属于各个Student对象。整个类中只有一份number拷贝,所有的对象都共享这份拷贝。
程序结果:


6966

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



