Example of a Class
A class
encapsulates state (
data members ) and behaviour ( function members, methods ).
The header
file point.h contains the declaration of the Point class.
The
implementation file point.cpp contains the code for the methods
of the Point class.
MyApp.cpp contains the code for an application that uses
the Point class.
point.h -- header file for the class Point
class Point
{
private:
double x;
double y;
public:
Point();
Point( /* in */
double argX, /* in */ double argY
);
~Point();
double GetX() const;
double GetY() const;
void SetPoint( /* in */ double argX,
/* in */ double argY);
void Write()
const;
void Add( /* in */
Point p );
};
point.cpp -- implementation of the Point class.
#include "point.h"
#include <iostream>
Point::Point()
{
x = 0.0;
y = 0.0;
}
Point::Point(
/* in */ double argX, /* in */ double argY )
{
x = argX;
y = argY;
}
Point::~Point()
{
}
double Point::GetX() const
{
return x;
}
double Point::GetY() const
{
return y;
}
void Point::SetPoint( /* in */
double argX, /* in */ double argY
)
{
x = argX;
y = argY;
}
void Point::Write() const
{
cout <<
"(" << x << "," << y <<
")";
}
void Point::Add( /* in */ Point
p )
{
x += p.x;
y += p.y;
}
MyApp.cpp --- an application that uses the Point class.
#include "point.h"
#include <iostream>
void main()
{
Point p1;
Point p2( 3,4 );
p1.SetPoint( 4, 5
);
p1.Add( p2 );
p1.Write();
cout
<< ' ' << p1.GetX() << endl;
}