重载>>对于C类的分数类 [英] overloading >> for a fraction class C++

查看:89
本文介绍了重载>>对于C类的分数类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图重载一个分数类的instream运算符>>。我创建了一个函数,可以从用户接受一个字符串,并解析为适当的参数为我的Fraction类,但我不确定如何实现这个在我的>>重载函数。

I'm trying to overload the instream operator >> for a fraction class. I've created a function that can take a string from the user and parse it into the proper arguments for my Fraction class but I'm unsure how to implement this in my >> overloading function.

用户可以输入三种类型的分数:
1.整数(例如5)
2.混合数字(例如2 + 4/5)
3.正规分数(例如1/2)

There are three types of fractions that a user can input: 1. whole numbers (e.g. 5) 2. mixed numbers (e.g. 2+4/5) 3. regular fractions (e.g. 1/2)

我的方法是在主函数中接受来自用户的字符串输入,解析它以获得有效分数类参数,然后将这个新创建的分数对象返回到流。

My approach was to accept this input as a string from the user in the main function, parse it to get the valid Fraction class parameters, then return this newly created fraction object to the stream. I'm just not sure how to do this.

在我的运算符重载定义中,我有:

In my operator overloading definition, I have this:

istream& operator>>(istream& in,const Fraction& input)

但是如果我接受一个字符串,这里的参数的类型应该是一个字符串吗?我只是很困惑这部分。我想要返回一个Fraction对象。下面是处理整数的例子。

But if I'm accepting a string, shouldn't the type of the parameter here be a string? I'm just very confused about that part. I want to then return a Fraction object. Here's an example of handling whole numbers.

    int num1 = atoi(input.c_str());
    Fraction output(num1);
    in >> output;
    return in;

我在正确的轨道上吗?

推荐答案

标准方法是将您的自定义输入操作分成三个部分:

The standard approach would be to break your custom input operation up into constituents:

std::istream & operator>>(std::istream & in, Fraction & input)  // not const!
{
  std::string token;

  if (!(in >> token)) { return in; }  // error

  int num, den;
  const bool res = parse_token(token, num, den);  // write this!

  if (!res)
  {
    in.setstate(std::ios::failbit);
    return in;
  }

  input.set(num, den); // or whatever
}

关键是写 parse_token(const std :: string& int& int& int&)< / code>函数,用于确定字符串是否表示有效分数,如果是,则将分子和分母放在两个变量中。

The crux is to write the parse_token(const std::string &, int &, int &) function that determines whether a string represents a valid fraction, and if yes puts the numerator and denominator in the two respective variables.

这篇关于重载&gt;&gt;对于C类的分数类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆