Implementing default constructors

Posted by James on Stack Overflow See other posts from Stack Overflow or by James
Published on 2010-05-09T06:31:16Z Indexed on 2010/05/09 6:38 UTC
Read the original article Hit count: 230

Filed under:
|

Implement the default constructor, the constructors with one and two int parameters. The one-parameter constructor should initialize the first member of the pair, the second member of the pair is to be 0. Overload binary operator + to add the pairs as follows:

 (a, b) + (c, d) = (a + c, b + d);   Overload the - analogously.  Overload the * on pairs ant int as follows:

 (a, b) * c = (a * c, b * c).

Write a program to test all the member functions and overloaded operators in your class definition. You will also need to write accessor (get) functions for each member.

The definition of the class Pairs:

class Pairs

{

public:

Pairs();

Pairs(int first, int second);

Pairs(int first);

// other members and friends

friend istream& operator>> (istream&, Pair&);

friend ostream& operator<< (ostream&, const Pair&);

private:

 int f;

 int s;

};

Self-Test Exercise #17:

istream& operator>> (istream& ins, Pair& second)

{

char ch;

ins >> ch; // discard init '('

ins >> second.f;

ins >> ch; // discard comma ','

ins >> second.s;

ins >> ch; // discard final '('

return ins;

}

ostream& operator<< (ostream& outs, const Pair& second)

{

outs << '(';

outs << second.f;

outs << ", " ;// I followed the Author's suggestion here.

outs << second.s;

outs << ")";

return outs;

}

© Stack Overflow or respective owner

Related posts about c++

Related posts about default-constructor