【问题标题】:Overriding iostream << results in error - C++ 11 [duplicate]覆盖 iostream << 导致错误 - C++ 11 [重复]
【发布时间】:2020-02-04 06:32:51
【问题描述】:

我正在为 C++ 学习练习创建一个与许多其他人一样的有理分数类。

我的一个要求是覆盖&lt;&lt; 运算符,以便我可以支持打印“分数”,即numerator + '\' + denominator

我已尝试关注this example,这似乎与this examplethis example 一致,但我仍然遇到编译错误:

WiP2.cpp:21:14: error: 'std::ostream& Rational::operator<<(std::ostream&, Rational&)' must have exactly one argument
   21 |     ostream& operator << (ostream& os, Rational& fraction) {
      |              ^~~~~~~~
WiP2.cpp: In function 'int main()':
WiP2.cpp:39:24: error: no match for 'operator<<' (operand types are 'std::basic_ostream<char>' and 'Rational')
   39 |     cout << "Two is: " << two << endl;
      |     ~~~~~~~~~~~~~~~~~~ ^~ ~~~
      |          |                |
      |          |                Rational
      |          std::basic_ostream<char>

我的代码如下:

#include <iostream>
using namespace std;

class Rational
{
    /// Create public functions
    public:

    // Constructor when passed two numbers
    explicit Rational(int numerator, int denominator){
        this->numerator = numerator;
        this->denominator = denominator;    
    }

    // Constructor when passed one number
    explicit Rational(int numerator){
        this->numerator = numerator;
        denominator = 1;    
    }

    ostream& operator << (ostream& os, Rational& fraction) {
    os << fraction.GetNumerator();
    os << '/';
    os << fraction.GetDenominator();

    return os;
    }

    private:
    int numerator;
    int denominator;
}; //end class Rational


int main(){
    Rational two (2);
    Rational half (1, 2);
    cout << "Hello" << endl;
    cout << "Two is: " << two << endl;
}

为什么我无法使用Rational 类中的覆盖函数来覆盖&lt;&lt; 运算符?

编辑 - 我看到有些人建议使用 friend。我不知道那是什么,正在做一些初步调查。在我的情况下使用朋友进行可能的工作比较可能对我作为 OP 和其他面临类似实现类型问题的人有益。

【问题讨论】:

标签: c++ c++11 overriding


【解决方案1】:

这些函数不能在类中实现,因为它们需要具有全局范围。

一种常见的解决方案是使用friend 函数https://en.cppreference.com/w/cpp/language/friend

使用friend 函数我得到你的代码在这里编译https://godbolt.org/z/CWWv0p

【讨论】:

  • 请在答案中添加代码,以便我接受。
猜你喜欢
  • 2011-06-15
  • 2018-07-21
  • 1970-01-01
  • 2016-12-17
  • 1970-01-01
  • 2017-03-31
  • 2016-09-09
  • 2012-04-20
  • 1970-01-01
相关资源
最近更新 更多