English 中文(简体)
C++级
原标题:overloading >> for a fraction class C++

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.

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)

我的做法是接受这一投入,将其作为主要功能使用者的一种扼杀手段,使其获得有效的框架类别参数,然后将这一新产生的部分退回到上游。 我不敢肯定如何做到这一点。

In my operator overloading definition, I have this:

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

但是,如果我接受一种扼杀,那么这里的参数类型就应当是一个扼杀吗? 我对这一部分感到非常困惑。 然后我要回去一个Fraction物体。 这里是处理全数的例子。

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

我在这里的正确轨道?

最佳回答

标准做法是打破您对习俗的投入,将其投入到选民中:

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 :string & int & int &>功能,确定扼杀是否构成有效分数,以及如果是将数字和分母放在这两个变量中的话。

问题回答

您的分数需要作为产出参数,因此可以tconst:

<代码>istream&营运人>>istream& in,Fraction&put>

然后,在您的职能范围内,您将摘录成“<>编码>。 您将相关数据储存在<条码>输入/编码><条码>上。

这里,我想说的是,因为其他人已经解释了问题。

class Fraction {
int top, bottom;
public:
    Fraction(int top_, int bottom_) :top(top_), bottom(bottom_) {}
    Fraction(const Fraction& rhs) : top(rhs.top), bottom(rhs.bottom) {}
    Fraction& operator=(const Fraction& rhs) {top=rhs.top; bottom=rhs.bottom; return *this}

    int get_numerator() {return top;}
    int get_denomerator() {return bottom;}
    double get_value() {return double(top)/bottom;}
};

istream& operator>>(istream& in, Fraction& input) {
    int numer;
    int denom=1;
    int whole=0;
    int peekchar;
    bool valid=false;

    in >> numer; //get the numerator
    peekchar = in.peek(); //peek at next character
    if(in && peekchar ==  + ) { //if next character is a +
        in.get(); //skip the + character
        whole = numer; //then first character was whole, not numerator
        in >> numer; //get the real numerator
        valid = true;
        peekchar = in.peek();
    }
    if(in && peekchar ==  / ) { //if next character is a /
        in.get(); //skip the / character
        in >> denom; //get the denominator
        valid = true;
    }
    if (in || valid) { //if we succeeded in reading
        if (denom == 0)
            denom = 1;
        numer += (whole*denom);
        input = Fraction(numer, denom);
     }
     return in;
}
ostream& operator<<(ostream& in,const Fraction& output) {
    return in << output.get_numerator() <<  /  << output.get_denominator();
}
int main() {
    Fraction my_fract;
    cout << "Enter a fraction
";
    cin >> my_fract;
    cout << "you entered " << my_fract;
}
}

页: 1 如果用户希望输入/输出到(<>string>上,则可以始终使用stringstream。 注意您的定义

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

在流语文中,这意味着从<代码>istream中提取,因此,你的输入参数应为t。 另一方面,在输出<代码>Fraction至ostream 声明

ostream& operator<<(ostream& in,const Fraction& input) //Here const is good

Also, one final note is that istream/ostream are specific implementations that work with char as element and the default traits. A more general implementation would work with any kind of stream, with operators defined like this

template< typename Elem, typename Traits >
std::basic_istream< Elem, Traits >& operator>>(std::basic_istream< Elem, Traits >& in, Fraction& input)

template< typename Elem, typename Traits >
std::basic_ostream< Elem, Traits >& operator<<(std::basic_ostream< Elem, Traits >& out, Fraction const& output)

关于您的<代码>oper>>功能,即你希望超负荷使用<代码>>>>>,而不是输入<代码>std:string, parse it,然后试图从平级参数中形成一个新的 标的,因此,你应当把用户投入放在“代码”内;>超载功能,因为已经直接获得投入。 换言之,你重复做的是多余的,把......与<代码>oper>>超载的物体相混为一谈,其用意应是从该用户投入中提取全部用户投入和创建的物体......在“编码>>Fraction之前不会经过两步。

因此,你们想要的是:

//set values of Fraction object through pass-by-reference
istream& operator>>(istream& in,Fraction& input);

并使用:

Fraction new_fraction_obj; //has only default-constructor-set values
std::cin >> new_fraction_obj;  //now will have the user-input values after call

最后,如果试图对用户投入进行分类,那么你发现,这种投入没有正确的格式,或者是错误的类型等,就会确定<代码>istream的不轨。 标的为ios:setstate(),从而使上游用户能够发现该投入有误,而正在逐个参照的物体则处于无效状态。





相关问题
Undefined reference

I m getting this linker error. I know a way around it, but it s bugging me because another part of the project s linking fine and it s designed almost identically. First, I have namespace LCD. Then I ...

C++ Equivalent of Tidy

Is there an equivalent to tidy for HTML code for C++? I have searched on the internet, but I find nothing but C++ wrappers for tidy, etc... I think the keyword tidy is what has me hung up. I am ...

Template Classes in C++ ... a required skill set?

I m new to C++ and am wondering how much time I should invest in learning how to implement template classes. Are they widely used in industry, or is this something I should move through quickly?

Print possible strings created from a Number

Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...

typedef ing STL wstring

Why is it when i do the following i get errors when relating to with wchar_t? namespace Foo { typedef std::wstring String; } Now i declare all my strings as Foo::String through out the program, ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

Window iconification status via Xlib

Is it possible to check with the means of pure X11/Xlib only whether the given window is iconified/minimized, and, if it is, how?

热门标签