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

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

本文关键字:lt C++ 错误 iostream 覆盖      更新时间:2023-10-16

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

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

我尝试遵循此示例,这似乎与此示例和此示例一致,但仍然出现编译错误:

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类中的 override 函数来重写<<运算符?

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

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

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

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