[英]something like virtual member(structure)
I have class A with basic members and functions: 我有A级基本成员和功能:
class A{
public:
typedef struct{
int aa;
int bb;
} stEntry;
stEntry entry;
void function1();
void function2();
};
Than class B that should extend class A including structure stEntry... 比B类更应该扩展A类包括结构stEntry ...
class B : public A{
public:
typedef struct :stEntry
{
int cc;
} stEntry;
stEntry entry;
void function3();
};
and then: 然后:
int main() {
A a;
B b;
a.entry.aa = 1;
b.entry.aa = 2;
b.entry.cc = 3;
cout << "class A:"<<sizeof(a)<< endl;
cout << "class B:"<<sizeof(b)<< endl;
return 0;
}
I get 我明白了
class A:8
class B:20
So class B contains 2 instances - 8 bytes(A class member) + 12 bytes(B class member). 所以B类包含2个实例--8个字节(A类成员)+ 12个字节(B类成员)。
Is there a way how to extend structure stEntry for class B? 有没有办法如何扩展B类的结构stEntry? (without have 2 instances)
(没有2个实例)
No, because you're creating two instances yourself . 不,因为你自己创建了两个实例 。 The base class has an instance, and the derived class has an instance (of a class extending the base class' inner class).
基类有一个实例,派生类有一个实例(扩展基类'内部类的类)。
You can't modify the structure of the base class outside of it - once you defined it, it stays like that. 你不能在它之外修改基类的结构 - 一旦你定义它,它就会保持这样。
Sort of, with virtual inheritance: 具有虚拟继承的排序:
struct stEntryBase {
int aa;
int bb;
};
struct A : virtual stEntryBase {
typedef stEntryBase stEntry;
void function1();
void function2();
};
struct stEntryDerived : virtual stEntryBase {
int cc;
};
struct B : A, stEntryDerived {
typedef stEntryDerived stEntry;
void function3();
};
If you want to go another level of inheritance then B
would derived virtually from stEntryDerived
. 如果你想进入另一个级别的继承,那么
B
将从stEntryDerived
派生出来。
Now you have to refer to the fields as a.aa
, b.cc
, there is no member entry
. 现在你必须将字段称为
a.aa
, b.cc
,没有成员entry
。 Also, the stEntry
types are no longer POD (so bb
and cc
may no longer be adjacent in memory). 此外,
stEntry
类型不再是POD(因此bb
和cc
可能不再在内存中相邻)。 Finally, the size increase due to the virtual inheritance might actually be bigger than two int
s. 最后,由于虚拟继承而导致的大小增加实际上可能大于两个
int
。
What you can do, is get an stEntryDerived*
or stEntryDerived&
from an instance of B
. 您可以做的是从
B
的实例获取stEntryDerived*
或stEntryDerived&
。 Then that pointer/reference can be used to access aa
, bb
, and cc
as the members of stEntryDerived
, without the user needing to know about B
. 然后,该指针/引用可用于访问
aa
, bb
和cc
作为stEntryDerived
的成员,而无需用户了解B
So you've achieved separation of interface, at some cost. 所以你已经实现了界面分离,但需要付出一些代价。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.