我知道子对象是成员子对象、基类子对象和数组。我找不到任何明确解释前两个术语的内容。以下面的代码为例:
struct A{int a;};
struct B{int b;};
struct C:public A,public B{};
Run Code Online (Sandbox Code Playgroud)
我认为:int a是一个可能的、尚未实例化的 A 类型对象的成员子对象;int a是一个可能的、尚未实例化的 C 类型对象的基类子对象。对吗?成员子对象和基类子对象的定义是什么?您能提供一些例子吗?
每当一个类继承另一个类时,它也会继承该类的一个实例:
\nclass A { };\nclass B : A { };\nRun Code Online (Sandbox Code Playgroud)\n那么B类内部看起来像:
\nclass B\n{\n A a; // <- implicit base class sub-object, not visible to you\n};\nRun Code Online (Sandbox Code Playgroud)\n请注意,在某些情况下甚至可能有多个 A!
\nclass A { };\nclass B : A { };\nclass C : A { };\nclass D : C, B { };\nRun Code Online (Sandbox Code Playgroud)\nD 的内部看起来像:
\nclass D\n{\n B b; // { A a; }\n C c; // { A a; }\n};\nRun Code Online (Sandbox Code Playgroud)\nwithb和c作为基类子对象;或以扁平表示形式:
class D\n{\n A aFromB; // inherited from B, but not a sub-object of D itself\n // other members of B\n A aFromC; // inherited from C, again not a sub-object of D\n // other members of C \n};\nRun Code Online (Sandbox Code Playgroud)\nB和C基类子对象在此表示中不可见,但它们仍然以相应实例与相应其他成员组合的形式存在A(想想有大括号)。
如果您想避免 的重复A,则需要虚拟继承:class B : virtual A { }\xe2\x80\x93 然后将所有虚拟继承(直接或间接)的实例A合并为一个实例(尽管如果存在非虚拟继承的实例,则这些实例仍保留在与合并的平行),考虑:
class A { };\nclass B : virtual A { };\nclass C : virtual A { };\nclass D : A { };\n\nclass E : B, C, D\n{\n A combinedAFromBAndC;\n // other members of B\n // other members of C\n A separateAFromD\n // other members of D\n};\nRun Code Online (Sandbox Code Playgroud)\n注意:上面的这些布局只是示例,具体布局可能会有所不同。
\n