您的位置:首页 > 移动开发 > Objective-C

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

2013-11-25 20:15 661 查看
  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。

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

// A class can have a static member of self type
#include<iostream>

using namespace std;

class Test
{
static Test self;  // works fine

/* other stuff in class*/

};

int main()
{
Test t;
getchar();
return 0;
}


  下面的程序也可运行。

// A class can have a pointer to self type
#include<iostream>

using namespace std;

class Test
{
Test *self;  // works fine

/* other stuff in class*/

};

int main()
{
Test t;
getchar();
return 0;
}


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

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

// A class can not have a non-static member of self type
#include<iostream>

using namespace std;

class Test
{
Test self;  // works fine

/* other stuff in class*/

};

int main()
{
Test t;
getchar();
return 0;
}


  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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: