高难度c++问题

bzxu 2002-05-07 12:39:08
class A{
public:
A(){}
A* getA(){return &_instance;}
private:
static A _instance;
};

定义一个对象
1 A a; sizeof(a)=? why?

2 if 定义A如下:
class A{
public:
A(){}
virtual A* getA(){return &_instance;}
private:
static A _instance;
};
A a; sizeof(a)=?
why?
请给出这两个类的对象模型。
...全文
24 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
prototype 2002-05-07
  • 打赏
  • 举报
回复
rigorously speacking, the size of a user-defined class is compiler-dependent. in other words, the answers for the problems could be 1, 2, 4, 8, or whatever number (up to the compiler). so one has to always use 'sizeof' to determine the size (rather than using some magic numbers) if s/he wants the code to be portable.

but for most compilers on a 32bit os, i believe the results are like what saucer(思归) said (and reasons for that are also explained correctly).
yoyoyosiyu 2002-05-07
  • 打赏
  • 举报
回复
1.第一个问题saucer(思归) 回答的是正确的。

2.第二个问题并不完全正确。答案要看你的编译环境。如果你不是用32位的操作系统,用的是16位系统,答案就会是 2 。正像是 afsfop 所说的“有virtual时需要增加vptr”,vptr 是一个指针。在32位操作系统中地址是用4个字节表示,那么指针也应该是4个字节。
SphereEGO 2002-05-07
  • 打赏
  • 举报
回复
楼上的已经回答得很清楚了。

谁能告诉我为什么 (象楼主里的例子):

当没有virtual函数时,内部的static datamember不用implement
而当有virtual函数时,内部的static datamember必须implement
saucer 2002-05-07
  • 打赏
  • 举报
回复
1. sizeof(A) == 1
the minimum size of an instance of a class is 1, it cannot be zero, since its instance needs to be allocated somewhere

2. sizeof(A) == 4
with virtual functions inside a class, each instance contains a hidden member variable, a pointer to the virtual table, which is normally 4 bytes in size

69,382

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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