structs原型中的继承

inheritance in structs prototypes

本文关键字:继承 原型 structs      更新时间:2024-04-28

是否可以在C++中表示:

struct foo {
int x;
int y;
struct A derived;
};
struct A {
int val;
};
struct B : A {
int baz[10];
};
struct C : A {
int baz[20];
};

其中derived可以是A的任何继承结构(B或C(,但不能是A,而不改变原型struct foo?例如,是否可以执行以下操作?

void func(void)
{
struct B b;
struct foo foo;
foo.derived = b;
}
struct A {
int val;
virtual ~A() = 0; // so nobody can instantiate A alone.
};
inline
A::~A() = default; // the destructor HAS to be defined.
struct foo {
int x;
int y;
std::unique_ptr<A> derived;
};

然后其他的都一样。。。和使用:

foo foo_v;  foo_v.derived = std::make_unique<B>();

请注意,我已经去掉了C语言元素,使其成为纯C++。我也会清理这些,让它们更有凝聚力。在上面的代码中,x和y没有初始化,这有意义吗?可能不会,所以应该有一个构造函数来强制提供它们,将它们设置为初始值,或者两者兼而有之。