Can a C++ class have an object of self type?

 

  A class declaration can contain static object of self type,it can also have pointer to self type,but it can not have a non-static object of self type。

  例如,下面的程序可运行。

 1 // A class can have a static member of self type
 2 #include<iostream>
 3 
 4 using namespace std;
 5 
 6 class Test 
 7 {
 8     static Test self;  // works fine
 9     
10     /* other stuff in class*/
11     
12 };
13 
14 int main()
15 {
16     Test t;
17     getchar();
18     return 0;
19 }

 

 

  下面的程序也可运行。

 1 // A class can have a pointer to self type
 2 #include<iostream>
 3 
 4 using namespace std;
 5 
 6 class Test 
 7 {
 8     Test *self;  // works fine
 9     
10     /* other stuff in class*/
11     
12 };
13 
14 int main()
15 {
16     Test t;
17     getchar();
18     return 0;
19 }

 

  但是,下面的程序会产生编译错误"field `self’ has incomplete type“。

  在VC 6.0下会产生编译错误"error C2460: 'self' : uses 'Test', which is being defined"。

 1 // A class can not have a non-static member of self type
 2 #include<iostream>
 3 
 4 using namespace std;
 5 
 6 class Test 
 7 {
 8     Test self;  // works fine
 9     
10     /* other stuff in class*/
11     
12 };
13 
14 int main()
15 {
16     Test t;
17     getchar();
18     return 0;
19 }

 

  If a non-static object is member then declaration of class is incomplete and compiler has no way to find out size of the objects of the class.

  如果在类的声明中,non-static对象是该类的成员,若该non-static对象是incomplete,那么,编译器没有办法获取该类对象的大小。

  

  static variables do not contribute to the size of objects. So no problem in calculating size with static variables of self type.

  由于类的对象的大小是由non-static数据成员构成的,当然, 这里仅仅是无继承的、无虚函数的类。所以static数据成员不构成类的对象的大小,因此,当类的声明中包含有该类的static objects时是没有问题的。

 

  For a compiler, all pointers have a fixed size irrespective of the data type they are pointing to, so no problem with this also.

  对于编译器而言,所有类型的指针有固定的大小(32位机器下4字节),与指针所指对象的数据类型没有关系,所以类声明中包含自身类型的指针是没有问题的。

 

  

 

 

 

  Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

 


  转载请注明:http://www.cnblogs.com/iloveyouforever/

  2013-11-25  20:14:30

 

posted @ 2013-11-25 20:15  虔诚的学习者  阅读(309)  评论(0编辑  收藏  举报