我無法理解如何在多重繼承情況下區分基類的多個實體。在尋找解決方案時,我只找到了有關的答案,virtual inheritance但這根本不能解決我的問題,因為我不希望在 inharitance 樹的末尾的最后一個類中有一個基礎實體。
在維基百科上,第一段指出:
如果沒有虛繼承,如果兩個類 B 和 C 繼承自類 A,而類 D 繼承自 B 和 C,則 D 將包含 A 的成員變數的兩個副本:一個通過 B,一個通過 C。這些將是使用范圍決議可獨立訪問。
但我沒有找到有關如何在我的情況下使用范圍解析度的任何資訊。
至于我的任務,(強制的和過于復雜的)類層次結構是:
class Vehicle
{
protected:
unsigned long uPrice;
char* szOwner; // for some reason, not allowed to use std::string in my homework...
public:
unsigned long GetPrice();
// ...
}
class Trailer : public Vehicle
{
protected:
unsigned long uWid;
unsigned long uHei;
unsigned long uLen;
unsigned long uMaxWeight;
public:
// ...
};
class Car : public Vehicle
{
protected:
unsigned long uWid;
unsigned long uHei;
unsigned long uLen;
char* szBrand;
public:
// ...
};
class Trailer_Car : public Trailer, public Car
{
private:
unsigned long uTotalMass;
public:
// ...
};
正如我上面所說的,我想要Vehicle在一個實體中的多個實體Trailer_Car(一個用于Car和一個用于Trailer)。這完全適用于:
Trailer_Car c(/*...*/, 3500, 1200);
std::cout << c.Trailer_Car::Car::GetPrice() << "\n"; // prints 3500
std::cout << c.Trailer_Car::Trailer::GetPrice(); // prints 1200
但是,在我的代碼中,我必須對一個非同構陣列(可以包含 4 個類中的任何一個)進行排序,并將 aTrailer_Car轉換Vehicle為error: 'Vehicle' is an ambiguous base of 'Trailer_Car'. 例子:
Vehicle** Arr = new Vehicle*[N];
// ...
Arr[i] = static_cast<Vehicle*>(new Trailer_Car); // error: 'Vehicle' is an ambiguous base of 'Trailer_Car'
我該如何解決這個問題?我知道錯誤來自于這樣的事實Arr[i]doesen't知道它Vehicle來自Trailer_Car于點,但仍然沒有類似于C 的想到。
因為我更習慣于使用C我只想讓Arr一個void**altough我不知道如何這種做法是在C 中,我問這對避免在C做C 的好。
uj5u.com熱心網友回復:
您可以使用指標型別的中間轉換來控制您獲得重復基類的哪個實體
Arr[i] = upcast<Car*>(new Trailer_Car);
或者
Arr[i] = upcast<Trailer*>(new Trailer_Car);
我建議避免對應該是隱式轉換的東西進行“真正的轉換”。它不會強迫編譯器做愚蠢的事情然后閉嘴,就像演員經常做的那樣。
template<typename S, typename T> S upcast(const T& t) { return t; }
這樣,這些行中的任何一行都會為您提供顯式指定目標型別的隱式轉換,然后是推斷目標型別 ( Vehicle*)的隱式轉換。
請注意,在存盤指向兩個Vehicle子物件中的一個或另一個的指標的程序中,您還要選擇排序邏輯將使用哪些資料。
此外,您不應使用newand手動管理動態記憶體delete,而應使用智能指標。您撰寫的一個或一個庫......但遵循單一職責原則,不要將記憶體管理與其他任何東西放在同一個類中。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/388762.html
上一篇:指標差異是在基于范圍的for回圈中查找向量中元素索引的有效方法嗎?
下一篇:回傳特征矩陣和臨時值
