让"cout << obj1 + obj2 << endl;"发挥作用
Making "cout << obj1 + obj2 << endl;" work
因此,我得到了类内运算符重载,用于obj1+obj2:
fraction operator+ (fraction op);
类似地,cout<lt;obj的工作原理是重载操作符重载ostream:
ostream& operator<< (ostream& os, fraction& frac);
然而,如果我试图将两者结合起来,一切都会变得一团糟。
fraction.cpp:77:27: error: no match for ‘operator<<’ in
‘std::operator<< [with _Traits = std::char_traits<char>]((* & std::cout), ((const char*)"Sum: "))
<< f1.fraction::operator+(f2)’
这是代码:
#include <iostream>
using namespace std;
class fraction
{
private:
int n, d;
public:
fraction ()
{
this->n = 1;
this->d = 0;
}
fraction (int n, int d)
{
this->n = n;
this->d = d;
}
int getNumerator ()
{
return n;
}
int getDenominator ()
{
return d;
}
fraction operator+ (fraction op)
{
return *(new fraction(this->n*op.d + op.n*this->d, this->d*op.d));
}
fraction operator- (fraction op)
{
return *(new fraction(this->n*op.d - op.n*this->d, this->d*op.d));
}
fraction operator* (fraction op)
{
return *(new fraction(this->n*op.n, this->d*op.d));
}
fraction operator/ (fraction op)
{
return *(new fraction(this->n*op.d, this->d*op.n));
}
};
ostream& operator<< (ostream& os, fraction& frac)
{
int n = frac.getNumerator();
int d = frac.getDenominator();
if(d == 0 && n == 0)
os << "NaN";
else if(d == 0 && n != 0)
os << "Inf";
else if(d == 1)
os << n;
else
os << n << "/" << d;
}
int main ()
{
fraction f1(2, 3);
fraction f2(1, 3);
cout << f1 << " " << f2 << endl;
/*
cout << "Sum: " << f1+f2 << endl;
cout << "Difference: " << f1-f2 << endl;
cout << "Product: " << f1*f2 << endl;
cout << "Quotient: " << f1/f2 << endl;
*/
return 0;
}
帮助。D:
眼前的问题是
ostream& operator<< (ostream& os, fraction& frac)
不会接受临时,因为frac
不是const
引用-将其更改为
ostream& operator<< (ostream& os, const fraction& frac)
两个分数之间的operator+
将返回一个临时的,该临时不能绑定到非const
引用。
还有非常严重的内存泄漏在这些情况下:
fraction operator+ (fraction )
{
return *(new fraction(this->n*op.d + op.n*this->d, this->d*op.d));
}
new
将返回一个动态分配的对象,然后从函数中复制并返回。
就像大多数人一样:
fraction operator+ (const fraction& op) const
{
return fraction(this->n*op.d + op.n*this->d, this->d*op.d);
}
(注意两个额外的常量和pass-by-reference)
相关文章:
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 呼叫运营商<<临时
- 如何防止clang格式在流运算符调用之间添加换行符<<
- <<操作员在下面的行中工作
- 什么是现实中的"endl"(或任何输出操纵器)?它是如何实现的,它如何与操作员<<一起工
- std::endl,在 Python 中是否有等价物?(返回 + 刷新)
- 运算符 << 操作加载的 API for std::endl?
- 我在 C++ 中创建了一个函数来递归反转字符串,但是之后如何使功能打印一个 endl?
- 可变参数模板函数:调用没有匹配函数,std::endl
- 如何显式调用运算符<<
- 模板推导不适用于 std::endl?
- std::cout << glGetString(GL_RENDER) << std::endl;抛出错误但不GL_Renderer或GL_Verision,我不知道为什么?
- std::flush 不起作用,而 std::endl 可以
- "cout<<count<<endl;"没有打印任何内容
- 模板操作员&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<
- 使用带有重载<<endl上的运算符
- 将std::endl传递给std::operator<<