[英]sizeof *this object
Code:代码:
#include <cstdio>
class myc {
int dummy;
public:
int si(){return sizeof(*this);}
};
class d_myc : public myc {
int d_dummy;
};
int main() {
myc a;
d_myc b;
printf("%d %d\n%d %d", a.si(), b.si(), sizeof(a), sizeof(b));
return 0;
}
output: output:
4 4
4 8
I expected:我期望:
4 8
4 8
Why were my expectations wrong?为什么我的预期错了?
sizeof
is resolved at compile-time, not run-time. sizeof
在编译时解析,而不是在运行时解析。 So sizeof(*this)
is equivalent to sizeof(myc)
.所以
sizeof(*this)
等价于sizeof(myc)
。
I do not know "Why were your expectations wrong" because I cannot read minds:).我不知道“为什么你的期望是错误的”,因为我无法读心:)。 But if you wrote sizeof(myc), sizeof(d_myc) the compiler would generate exactly the same code as for what you have coded above.
但是,如果您编写 sizeof(myc), sizeof(d_myc) 编译器将生成与您在上面编写的代码完全相同的代码。 myc has 1 int, assuming 32bit, so 4 bytes.
myc 有 1 个 int,假设是 32 位,所以 4 个字节。 d_myc has 2 ints => 8 bytes.
d_myc 有 2 个整数 => 8 个字节。
This is resolved at compile time:这是在编译时解决的:
class myc {
int dummy;
public:
int si(){return sizeof(*this);}
};
ie *this
is always myc and will never be d_myc
.即
*this
始终是 myc 并且永远不会是d_myc
。 To get what you want you will have to override the function in d_myc
to do the same in the derived as the base.为了得到你想要的,你必须覆盖 d_myc 中的
d_myc
以在派生的基础上做同样的事情。 This is because sizeof(d_myc)
includes the base class too.这是因为
sizeof(d_myc)
也包含基础 class。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.