![](/img/trans.png)
[英]c++ derived base class Friend function accessing private on Parent?
[英]C++: friend function, derived class
我有2個類,基類是“ Port”,派生類是“ VintagePort”。 據我所知,如果我使用基類的引用或指針指向派生類的對象,它將自動找到正確的方法,而不是用於引用或指針,而是准確地找到對象(如果方法是虛擬的)。
在我的情況下,您可以看到兩個類都有朋友功能“ operator <<”。 但是看起來當我在基類中使用指針時,它僅從基類中調用函數。 如果我使用“ cout << VintagePort”,它可以正常工作。 我的問題:它工作正常還是應該在代碼中修復某些問題?
std::ostream& operator<<(std::ostream& os, const Port& p)
{
os << p.brand << ", " << p.style << ", " << p.bottles << endl;
return os;
}
std::ostream& operator<<(std::ostream& os, const VintagePort& vp)
{
os << (const Port &) vp;
cout << ", " << vp.nickname << ", " << vp.year << endl;
return os;
}
VintagePort vp1;
VintagePort vp2("Gallo", "lekko brazowy", 50, "Blaze", 1990);
VintagePort vp3(vp2);
Port* arr[3];
arr[0] = &vp1;
arr[1] = &vp2;
arr[2] = &vp3;
for (int i = 0; i < 3; i++)
{
cout << ">>>>> " << i+1 << " <<<<<" << endl;
cout << *arr[i]; // call for base class instead derived class
arr[i]->Show();
}
編譯器現在不實際將指針指向繼承的類。 解決此問題的一種方法是在基類中具有虛擬函數以進行輸出,並在繼承基類的類中覆蓋它。 然后在輸出運算符中調用此虛擬方法。
在C ++中,多態只能通過虛函數來實現,並且operator<<
不是一個(並且不能用於您的目的,因為第一個參數是std::ostream
。如果需要這種行為,則采用簡單的方法在您的層次結構中提供了虛擬打印功能,並且有operator<<
轉發了執行動態調度的調用:
struct base { // Don't forget virtual destructors
virtual void print( std::ostream& ) const;
};
struct derived : base {
virtual void print( std::ostream& ) const;
};
std::ostream& operator<<( std::ostream& o, const base& b ) {
b.print( o );
return o;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.