Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
493 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...