How to Setup and Create a Simple Triangle Header File using
C++
1. Click here for the
source file. First, set up the Driver, here a file called triangle_driver.cpp
as follows:
//driver file ...it calls the
class
#include <iostream> //usually std lib headers in
other directories
#include "triangle.h" //local header
using namespace std;
int main()
{
triangle t1,t2, t3[10]; //just like declaring
//a variable
//t1,t2,
t3[10] are objects and not used
triangle t4(5, 6); //the numbers stand for base
and
//height
//t3 sets up
an array of 10 objects
cout <<"Area of triangle t4 equals "<< t4.area()<<endl;
t1.setBase(3); //can set values of variables using methods
t1.setHeight(4);
cout<<"Area of triangle t1 equals " << t1.area()<<endl;
t3[0].setBase(5);
t3[0].setHeight(6);
cout<<"Area of triangle t3[0] equals " << t3[0].area()<<endl;
system("pause");
return 0;
}
|
2. Next set up the header file, here named triangle.h
//write the prototypes/declare
data for the class
//header file
class triangle
{
//if you don't say public or
private, by
//default it is all private,
can mix public/private
//no order
public: //user accessed data, functions
//data has state, functions have behavior
//functions in classes are called methods
//just like prototypes
triangle(); //creates triangle objects
//constructor...never have
return types
//if no
parameters...it is called
//the default constructor
triangle(double, double); //not a default constructor
//constructor allows you to set base and height
void setBase(double);
void setHeight(double);
double area();
private:
//declaring
variables...never make
//variables something the user
can declare
//it gives him too much
power...this is dangerous
double base, height; //sort of global variable
//in the
implementation
//protected: //usually
use in cases of inheritance
};
|
3. Finally setup the implementation file, here named triangle.cpp
//implementation...write the
functions
#include <iostream>
#include "triangle.h"
using namespace std;
//syntax: return type if there
is one, write the class you are in :: //scope resolution operator, then the
name of the function
triangle::triangle() //creates
triangle objects
{//default
constructor
base=0; //typically in default
constructor
height=0; //initialize your variables
}
triangle::triangle(double
b, double h) //not a default constructor
{//never in your
parameter use the variable names given in the header
//or they will become local to
the function
base=b;
height=h;
}
void triangle::setBase(double b)
{
base=b;
}
void triangle::setHeight(double h)
{
height=h;
}
double triangle::area()
{// the 1./
required to create a decimal answer or truncation occurs
return (1./2)*base*height;
}
|
0 comments:
Post a Comment