[英]Double overloading the istream and ostream operators in C++
I have a Fraction class that allows the input of a fraction in the form of c/d. 我有一个分数类,允许以c / d的形式输入分数。 I can output and input fractions just fine, but when I modify them with my custom function, shown down below, it does nothing at all.
我可以很好地输出和输入分数,但是当使用下面显示的自定义函数修改分数时,它什么也没做。
I have the following overloaded >> and << operators: 我有以下重载>>和<<运算符:
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;
}
Furthermore, I have a function that makes two fractions so that they are with the same common denominator: 此外,我有一个函数可以将两个分数相乘,使它们具有相同的公分母:
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;
}
I then try to output the result in the main as so: 然后,我尝试将结果输出到主目录中,如下所示:
setEqualDen(Fa, Fb);
cout << "The fractions are " << Fa << " , " << Fb <<
endl;
This does not work. 这是行不通的。 Is there a necessary step such as double overloading the << and >> operators in C++, or is my syntax simply missing something?
是否有必要的步骤,例如在C ++中双重重载<<和>>运算符,还是我的语法只是缺少某些内容?
You want the &
in the function definition, because you need to pass by reference since you're modifying your `Fractions. 您需要在函数定义中使用
&
,因为在修改`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;
}
You need to check for input errors and skip whitespace. 您需要检查输入错误并跳过空格。 I suggest using a temporary for containing the first digit, as it could be either the whole number or the numerator.
我建议使用一个临时字符来包含第一个数字,因为它可以是整数或分子。 The differentiating needs to take place after the '/' is detected.
检测到“ /”后需要进行区分。
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.