【发布时间】:2020-02-04 06:32:51
【问题描述】:
我正在为 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 和其他面临类似实现类型问题的人有益。
【问题讨论】:
-
Should operator<< be implemented as a friend or as a member function? 的可能重复项。 TL;DR - 在签名前加上
friend。 -
您应该将其声明为具有一个参数的成员函数,或者声明为具有两个参数的独立函数。但不是两者兼而有之。
标签: c++ c++11 overriding