2016-11-25 72 views
2

假設我有一個叫做dog的類並繼承了它,一個名爲shepherd的類,現在我重載了我的基類的流操作符,但是現在當我爲派生類重載流操作符我希望它也輸出最初來自我的基類的變量。如何讓派生類的流操作符也輸出基類

顯然我可以複製粘貼用於重載基類流操作符的代碼,但我正在尋找一個更優雅的解決方案,它不涉及複製大量代碼(尤其是因爲實際示例中有更多變量在基類內)。

一個例子。

class Dogs 
{ 
public: 
int N_legs; 
bool hair_short; 
}; 

class Shepherd : public Dogs 
{ 
public: 
bool guarding; 
};  

std::ostream &operator<<(std::ostream &os, Dogs dogs) 
{ 
os << "the content of class dogs" << std::endl; 
os << dogs.N_legs << "\t" << dogs.hair_short << std::endl; 
return os; 
} 

現在我試着動態演員,但沒有奏效。在主

Dogs dogs; 
dogs.N_legs = 4; 
dogs.hair_short = true; 
std::cout << dogs << std::endl; 

Shepherd shepherd; 
shepherd.N_legs = 4; 
shepherd.guarding = true; 
std::cout << shepherd << std::endl; 

std::ostream &operator<<(std::ostream &os, Shepherd shepherd) 
{ 
os << dynamic_cast<Dogs>(shepherd); 

os << "The content of class shepherd" << std::endl; 
os << shepherd.guarding << std::endl; 
return os; 
}; 

某處現在,這會給我的輸出,僅由派生類變量(當你註釋掉動態轉換),但我也想有內容的基類。

+0

對於多態性(和'dynamic_cast')工作,你需要使用*引用*的指針。嘗試通過引用*將參數傳遞給輸出運算符*。最好作爲一個常量引用(分別是'const Shepherd&'和'const Dogs') –

回答

1

dyanamic_cast只適用於引用和指針,這就是爲什麼你的代碼無法編譯。您應該將參數類型更改爲const &,不僅用於修復錯誤,還用於避免不必要的複製。

std::ostream &operator<<(std::ostream &os, const Dogs& dogs) 
std::ostream &operator<<(std::ostream &os, const Shepherd& shepherd) 
{ 
os << dynamic_cast<const Dogs&>(shepherd); 
... 

BTW:對於這種情況static_cast就足夠了。

+0

謝謝,這樣可以完成工作 – LinG

0

dynamic_cast在這裏不是必需的,因爲您總是知道DogsShepherd的基類。只需使用static_cast

std::ostream &operator<<(std::ostream &os, const Shepherd& shepherd) 
{ 
    os << static_cast<const Dogs&>(sheperd); 

    os << "The content of class shepherd" << std::endl; 
    os << shepherd.guarding << std::endl; 

    return os; 
}; 
0

使用static_cast代替;你知道編譯時的基類型!

std::ostream &operator<<(std::ostream &os, Shepherd shepherd) { 
    os << static_cast<Dogs>(shepherd); 
    os << "The content of class shepherd" << std::endl; 
    os << shepherd.guarding << std::endl; 
    return os; 
} 

Here's a Wandbox link.