这些是我拥有的函数和 Struct 声明,不允许我更改它们。
DerivedA giveDerivedA ();
DerivedB giveDerivedB ();
struct Base{
QString elementId;
QString elementType;
};
struct DerivedA : Base {
int a;
int b;
};
struct DerivedB : Base {
int c;
int d;
};
但我需要的是这样的:
struct DerivedA : Base {
int a;
int b;
void create();
QString doc;
};
如何将这些方法和成员添加到我得到的结构中?
我的第一个想法是:
struct myA: DerivedA {
void create();
QString doc;
};
你有什么建议吗?
编辑:第二个选择(已选择)
struct myA{
void create();
QString doc;
private:
DerivedA derivedA;
};
最佳答案
这类似于人们在扩展标准库类时遇到的问题。如果你的基类没有虚拟析构函数,你就不能安全地继承它。在这种情况下,您必须使用自由函数(无论如何首选)或组合。
否则,你所拥有的就是好的。
关于c++ - 如何向结构添加新成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3210343/