Re: Constructor problem

From: Chiller (..._at_...)
Date: 04/10/04


Date: Sat, 10 Apr 2004 06:22:04 GMT

John,

I've taken your suggestion and included enum; however, when I output the
stored values to screen, all the values are int values. What I'm trying to
do is to be able to enter a value and unit and be able to output the same
value and unit. ie, if I input Distance a (5, m) I'd like to be able to
output the same. Once I've got this working my next step will be to
implement some overloaded operators to perform addition, subtraction etc on
any objects created by the class.

I've included what I've done so far below. If you compile and execute the
program you'll see what I mean by the output being in the wrong format.I'd
appreciate any advice on this.

Thanks

Distance.h

************************************
#ifndef DISTANCE_H

#define DISTANCE_H

#include <iostream>

using namespace std;

class Distance

{

public :

Distance (int, int) ; // constructor - takes int values

Distance (int) ; // constructor - takes int value

Distance (void) ; // default - zero

//access member functions

int number (void) const;

int measure (void) const;

private :

int nu ; // the value

int me ; // the unit of measure (m)

} ;

// provide an overload of "<<" for easy display

ostream& operator<< (ostream&, const Distance&);

#endif

Distance.cpp as follows:

*****************************************

#include "Distance.h"

#include <iostream>

using namespace std;

/*-------------------------------------------------------*\

| implementation of member functions |

\*-------------------------------------------------------*/

// constructor

Distance :: Distance (int n, int m) : nu(n), me(m) {}

Distance :: Distance (int n) : nu(n) {}

Distance :: Distance (void) : nu(0) {}

enum

{

m,

km,

};

// access functions

int Distance :: number (void) const

{

return nu;

}

int Distance :: measure (void) const

{

return me;

}

// provide an overload of "<<" for easy display

ostream& operator<< (ostream& out, const Distance& d)

{

out << "(" << d.number() << "," << d.measure() << ")" ;

return out;

}

/*-------------------------------------------------------*\

| test driver for the Distance class |

\*-------------------------------------------------------*/

#ifdef TEST_DISTANCE // .... Distance class .... test driver

int main (void)

{

// create test input

Distance a = Distance (6);

Distance b (4);

Distance c (2);

Distance d;

Distance e (5, m);

cout << a << endl << b << endl << c << endl << d << endl << e << endl;

cin.ignore();

return 0; // normal termination

}

#endif



Relevant Pages


Loading