| TIP: Click on subject to list as thread! | ANSI |
| echo: | |
|---|---|
| to: | |
| from: | |
| date: | |
| subject: | Re: C++ for beginners? |
From: Gregg N
Geo wrote:
> Ok, I want an opinion.
>
> Here is a question we just had on our midterm for this beginners C++ class,
> tell me if this sounds like a problem for beginners who had one 3 hour
> classroom session on "classes".
>
> Problem:
>
> Write a math class, which performs the four mathematical operations
> (addition, subtraction, multiplication & division) and consists of two data
> members. The class should be a template class and should accept int, float
> or double data types. The class should consist of constructors and
> destructor. Instantiate the class with different data types and in different
> ways (like: Math m(5,6); Math m1; m2=m1). The class is also supposed ot
> consist of a display member function, which would display the output from
> every function.
>
> that was 1 of 6 questions on the test...
>
> Geo. (we had 1.5 hours to do the test)
Was that the question verbatim? It is a little vague about how the
"two data members" are to be used. I think she is asking for you
to define a class that holds on to two numbers that you are going to add,
subtract, etc. This is a questionable use for a class. More interesting
would be to define a new data type like a complex number that supports the
operations of addition, subtraction, etc.
If it weren't for the template requirement, I would say it is a reasonable
question for 3 hours of C++ instruction. If you don't understand templates,
then the requirement to accept int, float, and double might not make sense
to you.
In any case, here is one solution. It compiles and runs using the free
version of Visual C++ 2003.
template
class Operands
{
public:
Operands(T a, T b) : a_(a), b_(b) { }
Operands(T a) : a_(a), b_(T()) { }
~Operands() { /* Nothing to do */}
T Add() { return a_ + b_; }
T Subtract() { return a_ - b_; }
T Divide() { return a_ / b_; }
T Multiply() { return a_ * b_; }
void ShowOps()
{
std::cout << "a=" << a_ << ",
b=" << b_ << std::endl;
}
void Display()
{
ShowOps();
std::cout << " Sum: " << Add() << '\n'
<< " Difference: " << Subtract()
<< '\n'
<< " Product: " << Multiply()
<< '\n';
if (b_ != 0)
std::cout << " Quotient: " << Divide()
<< '\n';
}
private:
T a_;
T b_;
};
int main() {
Operands op1(1);
op1.Display();
Operands op2(5, 6);
op2.Display();
Operands op3(3.14, 2.718);
op3.Display();
}
I hope this helps.
Gregg
--- BBBS/NT v4.01 Flag-5
* Origin: Barktopia BBS Site http://HarborWebs.com:8081 (1:379/45)SEEN-BY: 633/267 270 5030/786 @PATH: 379/45 1 396/45 106/2000 633/267 |
|
| SOURCE: echomail via fidonet.ozzmosis.com | |
Email questions or comments to sysop@ipingthereforeiam.com
All parts of this website painstakingly hand-crafted in the U.S.A.!
IPTIA BBS/MUD/Terminal/Game Server List, © 2025 IPTIA Consulting™.