C++:友元函数,派生类

ash*_*hur 0 c++ inheritance 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();    
}
Run Code Online (Sandbox Code Playgroud)

Som*_*ude 5

编译器现在指针实际上并不指向继承的类.解决此问题的一种方法是在基类中使用虚函数进行输出,并在继承基类的类中覆盖它.然后在输出运算符中调用此虚方法.