Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
498 views
in Technique[技术] by (71.8m points)

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)

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)

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;

Am I on the right track here?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your fraction is needed to be an output parameter so it can't be const:

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

Then inside your function, you would extract into a std::string which you then parse, and store the relevant data into your input Fraction object.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...