gpt4 book ai didi

c++ - 标准布局类上的偏移量?

转载 作者:行者123 更新时间:2023-11-30 04:11:36 33 4
gpt4 key购买 nike

#include <iostream>
#include <cstddef>
class Foo
{
int a;
int b;
float c;
};
int main()
{
Foo foo;
std::cout << offsetof(Foo, b) << std::endl;
return 0;
}

以上代码无法使用 gcc-4.8.2 或 vc++11 编译。错误消息是无法访问类 Foo 中的私有(private)成员 b。

但是按照标准,offsetof应该支持标准布局类,而Foo是标准布局类。

这是gcc-4.8.2或vc++11的缺陷,还是我对c++标准的理解有误?

最佳答案

offsetof 被定义为一个,因此它无法绕过访问控制并获得私有(private)成员的访问权限,我们可以看到这就是起草 C++ 标准部分 17.6.1.2 Headers 段落 5 的情况,其中说(强调我的 ):

Names which are defined as macros in C shall be defined as macros in the C++ standard library, even if C grants license for implementation as functions. [ Note: The names defined as macros in C include the following: assert, offsetof, setjmp, va_arg, va_end, and va_start. —end note ]

更新

所以有一些 hack 可以让您以标准方式访问类的私有(private)成员,但是如果我们回到 C99 草案标准,C++ 标准草案又回到了 offsetof然后我们在 7.17 Common definitions 3 中看到(强调我的):

   offsetof(type, member-designator)

which expands to an integer constant expression that has type size_t, the value of which is the offset in bytes, to the structure member (designated by member-designator), from the beginning of its structure (designated by type). The type and member designator shall be such that given

   static type t;

then the expression &(t.member-designator) evaluates to an address constant.

如果您试图从类外访问一个私有(private)成员,情况就不会如此。

关于c++ - 标准布局类上的偏移量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20170578/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com