在类中动态创建和删除内嵌类对象 为什么不改变类的大小 (内嵌类没有虚函数)

bolixin008 2006-11-07 11:15:52
#include "stdafx.h"
#include <windows.h>
// Two class :
// One contained a class in itself and have a variable object of that class
// Two contained a same struct class and dynamic create a object of that class
// Aim :
// Test the space and time spent to the two kind
// By the way , to test a array of a class for how to get the size

class COne
{
public:
int count;
class CTest
{
public:
char chArray[1000000];
};
CTest* CreateTest()
{
CTest* pTest= new CTest;
printf("Create new Test object!\n");
printf("and ths size of this is %d\n",sizeof(this));
return pTest;
}
bool SetContent()
{
CTest* ptest = CreateTest();
for (int i=0; i<10000; i++)
{
ptest->chArray[i] = 'a';
}
ptest->chArray[i] = '\0';
printf("and ths size of this is %d\n",sizeof(this));

delete ptest;
return true;
}
};

int main(int argc, char* argv[])
{
COne one;
printf("The size of COne before dynamic create object is %d\n\n",sizeof(one));
one.SetContent();
printf("The size of COne after dynamic create object is %d\n\n",sizeof(one));
return 0;
}
...全文
153 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
guochun 2006-11-07
  • 打赏
  • 举报
回复
类的大小已经定义是固定的,new在程序堆中分配内存
abblly 2006-11-07
  • 打赏
  • 举报
回复
sizeof(one)就是sizeof(COne),而COne的类的对象的大小就是由里面的成员变量和虚函数指针决定的,在你这个里面,就是由char chArray[1000000];决定的,而里面的方法的多少不影响类的对象的大小。
再说你的SetContent里面,CTest* ptest = CreateTest();新建了一个动态对象,对这个动态对象折腾了一番,然后又删除这个动态对象,根本不影响类的大小啊。
taodm 2006-11-07
  • 打赏
  • 举报
回复
呃,楼主,你要补的基础知识太多,让我不知道该如何讲解。
留给楼下吧。
你还是找本C++ Primer认真补课吧。

64,637

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧