//---------------------------------------------------------------- // // point-with-constructor.cpp // // Implements a point in two dimensional space. Based on the example // from Pohl, C++ by Dissection, pages 166-169, but with added // constructors. // // written by: Simon Parsons // modified : 13th March 2009 // //---------------------------------------------------------------- #include using namespace std; //---------------------------------------------------------------- // // point // The class point represents a location in a set of cartesian coordinates. // // It has two data members, an x and a y value, and three constructors. // The constructors initialise the data members. class point { private: double x, y; public: point() : x(0), y(0) { } // Default constructor point(double); // Convert double to point point(double, double); // Initialise both x and y if we are // given values for them. void print() const; void set( double u, double v ); double getX(); double getY(); }; // Constructors inline point::point(double u){ // Illustrates the use of "inline" x = u; } point::point(double x, double y){ // Shows one use of "this" this->x = x; this->y = y; } // Print the values void point::print() const { cout << "(" << x << "," << y << ")\n"; } // Set the values. void point::set( double u, double v ) { x = u; y = v; } // Accessor functions. We need these to get hold of x and y since they // are private. double point::getX(){ return x; } double point::getY(){ return y; } // End of point //---------------------------------------------------------------- // // Main program // This creates three instances of point, creating them in different ways, and // then printing out their contents. int main() { point a; point b(2.2); point c(2.3, 4.5); a.set(1.2, 3.4); cout << "point a = "; a.print(); cout << "point b = "; b.print(); cout << "point c = "; c.print(); } // end of main()