Παράδειγμα

Το παρακάτω παράδειγμα ορίζει και χρησιμοποιεί την κλάση point που - εξεζητημένα - εκμεταλλεύεται όλα τα στοιχεία που έχουν αναφερθεί:

point.h


class point {
private:
        int x, y;
        static int numpoints;
public:
        point();                        // Default contructor
        point(int sx, int sy);          // Other constructor
        ~point();                       // Destructor
        int getx() const;               // Access functions
        int gety() const;
        void display();                 // Display member function
        void setpos(int sx, int sy);    // Set position
        static int points_used();       // Return number of points
        friend double distance(point p1, point p2);     // Display friend function
        friend void display(point &p);  // Display friend function
};

point.cpp

#include "point.h"
#include <iostream.h>
#include <math.h>

int point::numpoints = 0;

point::point(int sx, int sy)
{
        x = sx;
        y = sy;
        numpoints++;
}

point::point()
{
        x = y = 0;
        numpoints++;
}

point::~point()
{
        numpoints--;
}

int
point::getx() const
{
        return (x);
}

int
point::gety() const
{
        return (y);
}

// Member function; used as a.display();
void
point::display()
{
        cout << "(" << x << "," << y << ")\n";
}

// Friend function; used as display(a)
void
display(point& p)
{
        cout << "(" << p.x << "," << p.y << ")\n";
}

double
sqr(double x)
{
        return (x * x);
}

double
distance(point p1, point p2)
{
        return (sqrt(sqr(p1.x - p2.x) + sqr(p1.y - p2.y)));
}

void
point::setpos(int sx, int sy)
{
        this->x = sx;
        point::y = sy;
}

int
point::points_used()
{
        return (numpoints);
}

main.cpp

#include <iostream.h>
#include "point.h"

main()
{
        point a(12);
        point b, *c;

        c = new point(55);
        b.setpos(66);

        a.display();            // Member function
        display(b);             // Friend function
        c->display();
        cout << "Distance from a to b = " << distance(a, b) << "\n";
        cout << "points used = " << point::points_used() << "\n";
        delete(c);
        cout << "points used = " << point::points_used() << "\n";
        return (0);
}