![](/img/trans.png)
[英]Error with 'ostream' and 'istream' in C++ trying to overloading
[英]Double overloading the istream and ostream operators in C++
我有一个分数类,允许以c / d的形式输入分数。 我可以很好地输出和输入分数,但是当使用下面显示的自定义函数修改分数时,它什么也没做。
我有以下重载>>和<<运算符:
ostream& operator<<(ostream &out, const Fraction &f)
{
char x = '/';
out << f.num;
out << x;
out << f.den;
return out;
}
istream& operator>>(istream &in, Fraction &r)
{
//in >> r;
int whole = 0, num, den = 1;
char next;
in >> num;
next = in.peek();
if(next == '+'){
in.get();
whole = num;
in >> num;
next = in.peek();
}
if(next == '/'){
in.get();
in >> den;
}
if(whole != 0){
num += (whole * den);
}
if(den == 0){
den = 1;
}
r.num = num;
r.den = den;
return in;
}
此外,我有一个函数可以将两个分数相乘,使它们具有相同的公分母:
void setEqualDen(Fraction a, Fraction b){
int tempa = a.den;
int tempb = b.den;
a.den *= tempb;
b.den *= tempa;
a.num *= tempb;
b.num *= tempa;
}
然后,我尝试将结果输出到主目录中,如下所示:
setEqualDen(Fa, Fb);
cout << "The fractions are " << Fa << " , " << Fb <<
endl;
这是行不通的。 是否有必要的步骤,例如在C ++中双重重载<<和>>运算符,还是我的语法只是缺少某些内容?
您需要在函数定义中使用&
,因为在修改`Fractions时需要通过引用传递。
void setEqualDen(Fraction &a, Fraction &b){
int tempa = a.den;
int tempb = b.den;
a.den *= tempb;
b.den *= tempa;
a.num *= tempb;
b.num *= tempa;
}
您需要检查输入错误并跳过空格。 我建议使用一个临时字符来包含第一个数字,因为它可以是整数或分子。 检测到“ /”后需要进行区分。
std::istream& operator>>(std::istream& inp, Fraction& f)
{
int temp = 0;
f.num = 0;
f.den = 1;
inp >> temp; // Could be whole number or numerator.
if (inp)
{
int whole = temp;
int numerator = 0;
inp >> numerator;
if (!inp)
{
// Let's assume that the input failed because of the '/' symbol.
numerator = temp;
whole = 0;
inp.clear();
}
else
{
inp.ignore(1000, '/'); // Skip over the '/'
}
int denominator = 1;
inp >> denominator;
if (denominator == 0) denominator = 1;
numerator += whole * denominator;
f.num = numerator;
f.den = denominator;
}
return inp;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.