我想實現一些具有多態性的類的層次結構,但我無法使其工作。 我有兩個問題:具有額外私有屬性的派生類
- 派生類中有多餘的私有變量
- 派生類的方法採取作爲參數的派生類的對象,並返回派生類的對象。
我可以使這個代碼工作,但以一種非多態的方式。這是簡化版本:
class Base
{
protected:
int mInt;
public:
Base(int iValue) : mInt(iValue) {}
virtual Base operator+(const Base otherBase)
{
Base result(otherBase.mInt + mInt);
return result;
}
};
class Derived : public Base
{
private:
double mDouble;
public:
Derived(int iValue, double dValue) : Base(iValue)
{
mDouble = dValue;
}
Derived operator+(const Derived otherDerived)
{
Derived result(otherDerived.mInt + mInt,
otherDerived.mDouble + mDouble);
return result;
}
};
int main()
{
Derived DobjectA(2,6.3);
Derived DobjectB(5,3.1);
Base* pBaseA = &DobjectA;
Base* pBaseB = &DobjectB;
// This does not work
Derived DobjectC = (*pBaseA)+(*pBaseB);
}
我如何設計類,使這項工作?
也許這可能有助於http://stackoverflow.com/questions/274626/what-is-object-slicing –
你期望什麼如果'pBaseB'實際上指向一個'Base'對象(或者任何其他派生類型 - 除了派生的 - 就此而言),會發生嗎? – Amit
@Amit我認爲最好的解決方案是拋出一個異常,如果pBaseB指出的類型不是派生的。 – Msegade