-
July 27th, 2009, 08:28 PM
#1
Class Methods Question
Hi,
I am kind of new to C++ class and wondering if someone can help me with following questions.
1. How to rewrite following method defination as a single line?
Rational Rational:: divide (const Rational & r) const
{
Rational t;
t = r.reciprocal();
t = multiply(t);
return t;
}
2. Choose the best prototype for a method to input an object of the class Rational from user.
A Rational Rational::input (void) const;
B Rational Rational::input (void);
C void Rational::input (void);
D void Rational::input (long & number, long & denom) const;
E void Rational::input (Rational & rat) const;
Any help would be greatly appreciated.
Thanks
Micky
-
July 28th, 2009, 02:19 AM
#2
Re: Class Methods Question
Originally Posted by micky_577
1. How to rewrite following method defination as a single line?
Obviously:
Code:
Rational Rational::divide(const Rational& r) const { Rational t; t = r.reciprocal(); t = multiply(t); return t; }
But you probably actually want to simplify it such that the member function is implemented with a single return statement. As such, simplify step by step: instead of creating a default Rational object and then assigning the result of r.reciprocal() to it, construct a Rational object as a copy of the result of r.reciprocal(). Instead of assigning the result of multiply(t) to t and then returning t, return the result of multiply(t). It would then be very easy to see how to eliminate the named variable and thus just have a single return statement.
By the way, note that I posted my code snippet in [code][/code] bbcode tags. Because I was making a joke, my example lacks proper formatting, but you should indent your code snippets properly.
Originally Posted by micky_577
2. Choose the best prototype for a method to input an object of the class Rational from user.
What do you think is the answer, and why?
Last edited by laserlight; July 28th, 2009 at 02:24 AM.
-
July 28th, 2009, 10:21 PM
#3
Re: Class Methods Question
Here is my try.
1. Rational Rational:ivide ( const Rational & r) const
{
return multiply (r.reciprocal());
}
2. Answer C
Please someone help.
Thanks
Micky
-
July 28th, 2009, 11:19 PM
#4
Re: Class Methods Question
Your answer to the first question looks correct.
The second question is kind of hard to answer without more information. What exactly is this input function supposed to do? Prompt the user and read input? Only read input? How is it going to handle failure (return a bool? use some default value? throw an exception)? What I'm trying to say is, "best prototype for an input method" is an extremely broad question. Of the given options though, B or C probably make the most sense.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|