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
最新文章
- juery学习总结(二)——juery操作页面元素
- HDU 5371 Hotaru&#39;s problem (Manacher,回文串)
- apk反编译(3)smali语法
- UVA 10537 The Toll! Revisited uva1027 Toll(最短路+数学坑)
- [React Fundamentals] Component Lifecycle - Updating
- Yet Another Scheme Introduction学习
- Play!framework 项目部署到Tomcat
- Fastjson介绍
- 哪些产品不用开发原生APP,微信公众号就够了?
- web自动化测试从入门到持续集成(selenium webdriver)
- Hystrix-request collapsing(请求合并)
- Android Multimedia框架总结(十七)音频开发基础知识
- 35 个最好用的 Vue 开源库
- Java编程的逻辑 (16) - 继承的细节
- 搭建自己的挂Q平台
- HibernateTemplate使用注意点
- clog,cout,cerr 输出机制
- php取得当前时间函数
- 基于jQuery悬停弹出遮罩显示按钮代码
- Facebook广告目标摘要