覆盖 iostream << 导致错误 - C++ 11

Overriding iostream << results in error - C++ 11

我正在创建 class 有理分数,就像许多其他人以前为 C++ 学习练习所做的那样。

我的一个要求是覆盖 << 运算符,以便我可以支持打印 "fraction",即 numerator + '\' + denominator

我试过this example, and that seems to be in line with this example and this 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 class 中的覆盖功能来覆盖 << 运算符?

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

这些函数无法在 class 中实现,因为它们需要具有全局作用域。

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

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