此问题已经在这里有了答案:
我正在像很多其他人一样创建一类Rational分数进行C ++学习。
我的要求之一是重写<<
运算符,以便我可以支持打印“分数”,即numerator + '\' + denominator
我已经尝试跟随this example,并且似乎与this example和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
类中使用覆盖功能来覆盖<<
运算符?
编辑-我看到有人建议使用friend
。我不知道那是什么,正在做一些初步调查。对于OP和其他面临类似实现类型问题的人来说,可能的比较工作方式对我的情况可能有利于我。
这些函数不能在类内部实现,因为它们需要具有全局作用域。
常见的解决方案是使用friend
函数https://en.cppreference.com/w/cpp/language/friend。
使用friend
函数,我在这里编译了您的代码https://godbolt.org/z/CWWv0p