C++11 c+中的POD类型和遗传+;11:为什么不能继承和扩展,仍然是POD类型

C++11 c+中的POD类型和遗传+;11:为什么不能继承和扩展,仍然是POD类型,c++11,inheritance,standard-layout,C++11,Inheritance,Standard Layout,我认为最好用一个例子来解释这一点: #include <iostream> struct A { int a; }; struct B { A a; int b; }; struct C: A { int c; }; static inline std::ostream& operator<< (std::ostream& os, const A& a) { return os << a.a;

我认为最好用一个例子来解释这一点:

    #include <iostream>

struct A
{
    int a;
};
struct B
{
    A a;
    int b;
};
struct C: A
{
    int c;
};

static inline std::ostream& operator<< (std::ostream& os, const A& a)
{ return os << a.a; }
static inline std::ostream& operator<< (std::ostream& os, const B& b)
{ return os << b.a << " " << b.b; }
static inline std::ostream& operator<< (std::ostream& os, const C& c)
{ return os << c.a << " " << c.c; }

static_assert(std::is_pod<B>::value, "B");
static_assert(std::is_pod<A>::value, "A");
static_assert(std::is_trivial<C>::value, "C");
//static_assert(std::is_pod<C>::value, "C");

int main()
{
    std::cout << "sizeof(A) " << sizeof(A) << std::endl;
    std::cout << "sizeof(B) " << sizeof(B) << std::endl;
    std::cout << "sizeof(C) " << sizeof(C) << std::endl;
    B b = B{14,42};
    std::cout << "b " << b << std::endl;
    C c; c.a=15; c.c=43;
    std::cout << "c " << c << std::endl;
    B* bp = &b;
    std::cout << "(C)b " << *(C*)(bp) << std::endl;
    C* cp = &c;
    std::cout << "(B)c " << *(B*)(cp) << std::endl;

    return 0;
}

为什么
C
不符合标准布局。正如我所料,它的内存布局与
B
相同。可能有什么不同?

也许可以帮助您?
C
中断的部分是“没有包含非静态数据成员的基类”。还请注意,C++14中的规则已更改。可能重复,可能。。。不确定在这种情况下,你的逻辑是否也存在同样的问题,但一般来说并不成立@TroelsBlum这也是我的理解。@TroelsBlum在我的示例中它们确实都是POD类型,但是
C
被布置为
A
,然后
B
,而
D
的布局只是
B
(因为基类是空的)。换句话说,在一般情况下,有一些示例表明基类的布局必须与初始成员的布局不同。
sizeof(A) 4
sizeof(B) 8
sizeof(C) 8
b 14 42
c 15 43
(C)b 14 42
(B)c 15 43