关于静态数据成员的简单却容易出错的小程序

 1 #include "iostream"
 2 using namespace std;
 3 class complex   //声明complex类
 4 {
 5 public:
 6     complex();
 7     void  display();
 8 private:
 9     static int r; //声明数据成员r是静态的
10     static int i;
11 };
12 int complex::r=0; //为静态数据成员r赋初始值
13 int complex::i=1;
14 complex::complex( )
15 {
16     r++;
17     i++;
18     cout<<"from constructure: r="<<r<<"  i="<<i<<endl;
19 }
20 void complex::display( )
21 {
22     cout<<"from display: r="<<r<<"  i="<<i<<endl;
23 }
24 int main()
25 {
26     complex *p[3];  //声明一个指针数组,该数组中含有3个指向complex类对象的指针。
27     complex b[3];   
28     for(int i=0;i<3;i++)
29     {
30       p[i]=&b[i];
31       p[i]->display();
32     }
33 return 0;
34 }

运行结果:

from constructure: r=1 i=2

from constructure: r=2 i=3

from constructure: r=3 i=4

from display: r=3 i=4

from display: r=3 i=4

from display: r=3 i=4

Press any key to continue................

简单来看这个小程序,超级简单无比。直接看到运行结果的话,也觉得顺理成章,不存在任何问题。

对于静态数据成员,类的所有对象共用相同的存储区,即整个类的所有对象共享静态数据成员。

可是,为什么很多同学还是信心十足地喊出如下运行结果:

from constructure: r=1 i=2

from constructure: r=2 i=3

from constructure: r=3 i=4

from display: r=1 i=2

from display: r=2 i=3

from display: r=3 i=4

Press any key to continue................

此外,从运行结果还可以看出如下结论:

(1)第26行在声明对象指针时并没有创建对象,因此也就谈不上去调用构造函数;

(2)第27行并不是简单的声明对象,而是创建了对象,所以调用了构造函数才有"from constructure"内容的输出。