简体   繁体   English

类定义中的sizeof(* this)

[英]sizeof(*this) in class definition

Can we do something like this: 我们可以做这样的事情:

#include <iostream>

class Foo
{
public:
   Foo() { std::cout << sizeof(*this) << '\n'; }
};

In C Standard i see the following: 在C标准中,我看到以下内容:

ISO/IEC 9899:2011 ISO / IEC 9899:2011

6.7.2.1 Structure and union specifiers 6.7.2.1结构和联合说明符

8 ... The type is incomplete until immediately after the } that terminates the list, and complete thereafter. 8 ...类型不完整,直到终止列表的}之后,然后完成。

But in C++ Standard i can't find any analogue. 但在C ++标准版中我找不到任何类比。

The sizeof operator shall not be applied to an expression that has incomplete type, so can we write such code or not? sizeof运算符不应该应用于具有不完整类型的表达式,那么我们可以编写这样的代码吗?

Yes, you can write such code because the compiler has to treat it as though the class definition is complete inside class method implementations. 是的,您可以编写此类代码,因为编译器必须将其视为类定义在类方法实现中完成。

For example it has to treat it as though you wrote: 例如,它必须像对待你一样对待它:

#include <iostream>

class Foo
{
public:
   Foo();
};

// Methods declared in the body of a class are implicitly inline
// Inline, however, probably doesn't mean what you think it means:
inline Foo::Foo() { std::cout << sizeof(*this) << '\n'; }

在成员函数体内部,类是完整的 - 否则,您无法访问任何其他成员函数,也无法访问任何成员变量,这将成为一个相当无价值的成员。

Yes you can write and also the result will also be correct. 是的你可以写,结果也是正确的。

#include<iostream>
using namespace std;
class Foo
{
public:
       int x;
   Foo() { std::cout << sizeof(*this) << '\n'; }
};
int main(){
    Foo b;
    b.x=5;
    system("pause");
    return 0;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM