gpt4 book ai didi

c++ - 警告 : offset of on non-standard-layout type 'DerivedClass'

转载 作者:行者123 更新时间:2023-11-30 01:35:35 41 4
gpt4 key购买 nike

我需要摆脱这个警告。据我了解,这似乎是因为 DerivedClass 不被视为普通旧数据。我读了关于 POD 的 cppreference和 Standard Layout Type但我仍然不明白为什么 DerivedClass 不是 POD。如果我将 BaseClass 的成员放入 DerivedClass 并且不使用继承 - 那么一切都很好。我使用 C++11

这是一个例子:

#include <iostream>

using namespace std;

class BaseClass
{
public:
int a;
};

class DerivedClass : public BaseClass
{
public:
int b;
};

int main(int argc, char *argv[])
{
// warning: offset of on non-standard-layout type 'DerivedClass'
int offset = offsetof(DerivedClass, b);

cout << offset;
}

感谢任何帮助。

最佳答案

这些是标准布局类型的要求:

All non-static data members have the same access control

Has no virtual functions or virtual base classes

Has no non-static data members of reference type

All non-static data members and base classes are themselves standard layout types

直到 C++14:

Either

has no base classes with non-static data members, or

has no non-static data members in the most derived class and at most one base class with non-static data members

Has no base classes of the same type as the first non-static data member (see empty base optimization)

这部分适用于这个例子:

has no base classes with non-static data members,

在您的情况下,您有一个包含非静态数据成员的基类。删除 a 会删除警告。

C++14之后,也有类似的约束,两个类中不能有成员,只能有一个:

Has all non-static data members and bit-fields declared in the same class (either all in the derived or all in some base)

关于c++ - 警告 : offset of on non-standard-layout type 'DerivedClass' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53850100/

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