有人可以帮助我理解从多个类继承的类如何保留一个类的某些属性值和另一个类的其他某些属性值。
(以及如何针对某些功能执行此操作)
这里有一些代码来描述该问题。
这是一种存在菱形继承结构的情况:
------------- 基础
----------/----------------\
-----/--------------------\
---母亲-------------父亲
---\-----------------------/
------\------------------/
---------\-------------/
------------ child
目标是继承 Father
类和Mother
类(显然来自 Base
类),但保留 y
Father
的值和 z
值来自Mother
。我只是不知道该怎么做。
我认为以下代码的问题在于调用构造函数的顺序使得Father
构造函数覆盖z
值 Mother
构造函数在初始化之前。
我想我可能需要做一个特别的 private
/protected
Father
不初始化 z
的构造函数还有一个特别的private
/protected
Mother
不初始化 y
的构造函数并显式调用这些构造函数。
但是我不知道这是正确的方法还是有更好的方法。有谁知道更好的方法吗?
#include <iostream>
class Base {
protected:
int x;
int y;
int z;
public:
Base(void) : x(0) {}
};
/* — — — — — — — — — — — — — — — — — — — — */
class Father
: public virtual Base {
public:
Father(void) : Base() {
y = 1;
z = 1;
}
};
/* — — — — — — — — — — — — — — — — — — — — */
class Mother
: public virtual Base {
public:
Mother(void) : Base() {
y = 2;
z = 2;
}
};
/* — — — — — — — — — — — — — — — — — — — — */
class Child
: public Mother, public Father {
public:
Child(void) : Base() {
y = Father::y;
z = Mother::z;
}
int getX() { return x; };
int getY() { return y; };
int getZ() { return z; };
};
/* — — — — — — — — — — — — — — — — — — — — */
int main() {
Child newborn;
std::cout << newborn.getX() << std::endl
<< newborn.getY() << std::endl
<< newborn.getZ() << std::endl;
return (0);
}
/* — — — — — — — — — — — — — — — — — — — — */
Output:
0
1
1
——— VS ———
Desired Output:
0
1
2
最佳答案
你不能这样做。
virtual inheritance旨在不重复成员。
知道这一点:
Child::x
、Mother::x
和Father::x
是完全相同相同的变量Child::y
、Mother::y
和Father::y
是完全相同相同的变量Child::z
、Mother::z
和Father::z
是完全相同相同的变量
这只是访问内存堆栈上同一变量的三种方法。因此,当您编写 y = Father::y;
时,它与您编写 y = y;
完全相同,对于其他变量依此类推。
如果您确实想在不更改设计的情况下做到这一点,也许您可以在 Father
和 Mother
中存储一个额外的变量,其中包含您想要的预设,只需通过范围解析将其提供给Child
即可。
父亲
、母亲
和 child
可能看起来像:
class Father : public virtual Base
{
protected:
int preset;
public:
Father() : preset(1)
{
y = preset;
z = preset;
}
};
class Mother : public virtual Base
{
protected:
int preset;
public:
Mother() : preset(2)
{
y = preset;
z = preset;
}
};
class Child : public Mother, public Father
{
public:
Child()
{
y = Father::preset;
z = Mother::preset;
}
int getX() const {return x;}
int getY() const {return y;}
int getZ() const {return z;}
};
而且只需做很少的改变就可以达到目的。
总而言之,我想说,对于每个需要多重继承的问题,至少有一种其他解决方案(更好的设计),它并不意味着多重继承(这只是我的观点)。
因此,我建议您重新考虑您的设计,而不是使用我在这里提出的解决方法。
关于C++:对于继承多个类的类,如何从一个类继承某些属性,从另一个类继承其他属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57105923/