【问题标题】:inheriting friend operators in C++在 C++ 中继承友元运算符
【发布时间】:2012-09-21 00:03:07
【问题描述】:

所以我有 A 类和 B 类,其中 B 类扩展了 A 类。我必须在两个类中重载 >。我希望在 B 类的运算符的函数定义中,我可以从 A 类调用重载的运算符,但这样做时遇到了麻烦。

#include <iostream>
#include <string>
using namespace std;

class A {
friend ostream& operator<<(ostream& out, A a);
protected:
    int i;
    string st;
public:
    A(){
        i=50;
        st = "boop1";
    }
};

ostream& operator<<(ostream &out, A a) {
out << a.i << a.st;
return out;
}

class B : public A {
friend ostream& operator<<(ostream& out, B b);
private:
    int r;
public:
    B() : A() {
        r=12;
    }
};

ostream& operator<<(ostream &out, B b) {
out = A::operator<<(out, b);    //operator<< is not a member of A
out << "boop2" << b.r;
return out;
}

int main () {
B b;
cout << b;
}

我尝试在B的operator

另外,请注意,实际上 A 和 B 有自己的头文件和正文文件。

【问题讨论】:

  • 您是否考虑过让运算符重载成为 A 的成员?
  • @Borgleader:你不能让 operator
  • @SethCarnegie:由于答案已经确定,我删除了我的评论(我知道这是错误的;)
  • @bstamour:哦,你是对的 -.-;

标签: c++ inheritance operators


【解决方案1】:

您可以使您的 B 对象看起来像 A 对象:

std::ostream& operator<< (std::ostream& out, B const& b) {
    out << static_cast<A const&>(b);
    out << "boop2" << b.r;
    return out;
}

请注意,您几乎肯定不想传递要按值打印的对象。我已将签名更改为使用const&amp;:这表明对象不会被更改,也不会被复制。

【讨论】:

  • 我应该在几个小时前就问这个问题,但是......我如何对操作员做同样的事情>>?
  • 好吧,对于输入,您想使用非常量引用,即演员表将是 static_cast&lt;A&amp;&gt;(b)
【解决方案2】:

Aoperator&lt;&lt; 确实不是A 的成员,而是在命名空间范围内。这里正确的方法是使用类型强制来让重载解析做正确的事情。变化:

out = A::operator<<(out, b);

到:

out << static_cast<A>(b);

另外,您应该更改您的运算符以使用const&amp; 获取第二个参数,在这种情况下,它应该如下所示以避免额外的副本:

out << static_cast<A const&>(b);

【讨论】:

    【解决方案3】:

    它们是全局函数,不要使用范围解析运算符来限定它们:

    operator<<(out, static_cast<const A&>(b)) << "boop2" << b.r;
    

    你必须强制转换它,这样你就不会调用你所在的函数并获得无限递归。另外,不要将operator&lt;&lt; 的结果赋值给out;它行不通,也不是你想做的。

    你的函数也应该接受const A&amp;'s 和const B&amp;'s(也就是说,你应该接受const 引用的参数,而不是值)以防止不必要的复制。

    【讨论】:

      猜你喜欢
      • 2015-11-19
      • 1970-01-01
      • 1970-01-01
      • 2021-05-10
      • 2011-04-22
      • 2015-02-09
      • 2011-12-05
      • 2021-06-07
      • 2012-04-05
      相关资源
      最近更新 更多