简体   繁体   English

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

[英]C++: friend function, derived class

I've got 2 classes, base class is "Port" and derived class is "VintagePort". 我有2个类,基类是“ Port”,派生类是“ VintagePort”。 As far as I know If i use reference or pointer of base class to object of derived class, it automatically finds correct method, not for reference or pointer but exactly to object(if methods are virtual). 据我所知,如果我使用基类的引用或指针指向派生类的对象,它将自动找到正确的方法,而不是用于引用或指针,而是准确地找到对象(如果方法是虚拟的)。

In my situation you can see both classes have friend function "operator<<". 在我的情况下,您可以看到两个类都有朋友功能“ operator <<”。 But it looks like when I'm using pointer for base class, it calls function only from base class. 但是看起来当我在基类中使用指针时,它仅从基类中调用函数。 If I use "cout << VintagePort" It works ok. 如果我使用“ cout << VintagePort”,它可以正常工作。 My question: Is it working correctly or I should fix something in code? 我的问题:它工作正常还是应该在代码中修复某些问题?

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();    
}

The compiler doesn't now the pointer actually points to an inherited class. 编译器现在不实际将指针指向继承的类。 One way to solve this is to have a virtual function in the base class for output, and override it in the class inheriting the base class. 解决此问题的一种方法是在基类中具有虚拟函数以进行输出,并在继承基类的类中覆盖它。 Then call this virtual method in the output operator. 然后在输出运算符中调用此虚拟方法。

In C++ polymorphism can only be achieved by means of virtual functions, and operator<< is not one (and cannot be for your purposes, since the first argument is the std::ostream . If you need this sort of behavior, the simple approach is providing a virtual print function in your hierarchy, and have operator<< forward the call performing dynamic dispatch: 在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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM