覆盖 iostream <<会导致错误 - C++ 11
Overriding iostream << results in error - C++ 11
我正在创建一个有理分数类,就像许多其他人以前为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
相关文章:
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 呼叫运营商<<临时
- 如何防止clang格式在流运算符调用之间添加换行符<<
- <<操作员在下面的行中工作
- 如何显式调用运算符<<
- 模板操作员&lt;未打电话
- C / CUDA中的模板方法是3个角括号(&lt;&lt;&lt;)
- C - 创建矢量&lt; vector&lt; double&gt;&gt;矩阵具有分配而不是inizializ
- 错误:调用"std::vector<:vector<int>>::p ush_back(std::vector<std::__cxx11::basic_string<
- C 建造者Clang STD :: Sill,找不到超载的操作员&lt;
- 为什么STD :: MAP需要操作员&lt;以及我如何写一个
- 为什么“操作员”需要const但不是为“运营商&lt;”
- 为什么将此对向量&lt; map&lt; int,int&gt;&gt;中的地图进行更新.失败
- C :对矢量进行排序&lt; struct&gt;(结构有2个整数)基于结构的整数之一
- 明确的专业化“ CheckIntmap&lt;&gt;”实例化
- 什么是模板&lt;&gt;inline bla bla
- 左角支架解释为操作员&lt;而不是模板参数
- 编辑C Qlist&lt; object*&gt; gt;QML代码和一些QML警告中的模型
- 超载操作员&lt;&lt; - 必须是二进制操作员
- 没有匹配的“运营商&lt;&lt;”