【问题标题】:How should I call an overloaded operator in a base abstract class?我应该如何在基本抽象类中调用重载运算符?
【发布时间】:2012-03-11 04:32:34
【问题描述】:

所以我有一个Base 类:

class Base
{
public:
    std::ostream& operator << (std::ostream & out, const Base & base);
}

我已经定义了操作员应该做什么:

ostream& operator << (std::ostream & out, const Base & base)
{
    return out << "output";
}

如果我有一个扩展BaseDerived 类,并且我希望Derived 在调用其插入运算符时执行与Base 相同的操作,那么执行此操作的最佳方法是什么?最好的意思是不重用代码的最佳方法。

【问题讨论】:

  • 您是否尝试过virtual 方法,其中仅当Derived 的行为与Base 不同时才进行覆盖?
  • 您的运营商声明无效。
  • @AustinMoore 除非涉及私有变量,否则不会。此外,ostream&amp; operator &lt;&lt; (ostream&amp;, const Base&amp;) 需要在命名空间范围内定义,即类定义的外部
  • @AustinMoore 您必须使用前向声明。示例:pastebin.com/4PPf3i3D

标签: c++ inheritance operator-overloading


【解决方案1】:

如果您想在派生类中使用基类方法,请限定调用:

void Derived::func()
{
   //whatever else you want to do first
   return Base::func();
}

除非方法是private,否则您可以访问它,因为DerivedBase

【讨论】:

    猜你喜欢
    • 2021-11-13
    • 1970-01-01
    • 2016-07-15
    • 2012-06-16
    • 1970-01-01
    • 1970-01-01
    • 2018-02-22
    • 2015-05-09
    • 2015-01-20
    相关资源
    最近更新 更多