我发现这个答案的输出因所使用的 gcc 编译器的版本而异。
#include<iostream>
using namespace std;
class ABC{
int x;
public:
void show(){
cout<<sizeof (this);
cout<<sizeof (*this);
}
};
int main(){
ABC ob;
ob.show();
return 0;
}
此代码在 4.9.1 版本中给出了 84 的输出,同样在之前的版本中给出了 44。
谁能给我解释清楚“this”指针背后的概念是什么?
最佳答案
this
指针在 N3337 [class.this] 中定义:
1
In the body of a non-static (9.3) member function, the keywordthis
is a prvalue expression whose value is the address of the object for which the function is called. The type ofthis
in a member function of a classX
isX*
.
所以 sizeof(this)
没有什么特别的。正如 deviantfan 指出的那样,您很可能正在观察编译 32 位程序与 64 位程序的效果。
带有 -m32
的 GCC 输出 44
和 84
没有。
关于c++ - cpp 中此指针的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27400267/