Simple Class Declaration Example
//A canonical example of a class declaration and
//implementation is a complex number class.
//Here follows the class declaration.
class Complex { //begin declaration
public: //all public members follow
Complex(double x, double y); //declaration of constructor
~Complex(); //declaration of destructor
//put here accessor functions
double Re();
double Im();
double Mod();
//put here operations
protected: //all protected members follow, perhaps none
private: //all private members follow, state data members
double _x; //real component
double _y; //imaginary component
//alternatively
// double _r; //radius
// double _theta; //argument
//by making the state data members private the
//implementor is free to change between these two
//implementation of a complex number without affecting
//the public member function declarations.
}; //end declaration with curly brace and semicolon
//The member function definitions might look something
//like this:
Complex::Complex(double re, double im) { //begin definition of constructor
_x=re;
_y=im;
}
Complex::~Complex(){
//does nothing
}
double Complex::Re(){
return _x;
}
double Complex::Im(){
return _y;
}
double Complex::Mod(){
double z;
z = sqrt(x*x + y*y); //sqrt in math library
}
etc....
Last edited by:
Jenny Williams
Last modification: 11 Mar 2001
Last significant update: ?1999
|