【问题标题】:C++: friend function, derived classC++:友元函数,派生类
【发布时间】:2012-07-20 11:26:27
【问题描述】:

我有 2 个类,基类是“Port”,派生类是“VintagePort”。 据我所知,如果我使用基类的引用或指针指向派生类的对象,它会自动找到正确的方法,而不是引用或指针,而是准确地指向对象(如果方法是虚拟的)。

在我的情况下,你可以看到两个类都有友元函数“operator

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

【问题讨论】:

  • 我认为程序运行正常。它正在执行函数std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, const Port&amp; p),因为您传递的参数确实是指向Port,而不是VintagePort,所以它调用与参数列表匹配的函数。在此示例中,继承无关紧要,因为

标签: c++ inheritance derived-class


【解决方案1】:

编译器现在没有指针实际指向一个继承的类。解决这个问题的一种方法是在基类中有一个虚函数用于输出,并在继承基类的类中覆盖它。然后在输出操作符中调用这个虚方法。

【讨论】:

    【解决方案2】:

    在 C++ 中,多态性只能通过虚函数来实现,而 operator&lt;&lt; 不是一个(也不能用于您的目的,因为第一个参数是 std::ostream。如果您需要这种行为,则简单的方法是在您的层次结构中提供虚拟打印功能,并让operator&lt;&lt; 转发执行动态调度的调用:

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

    【讨论】:

      猜你喜欢
      • 2015-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-24
      • 1970-01-01
      • 1970-01-01
      • 2011-01-09
      相关资源
      最近更新 更多