In the previous section, there were two files. The gaussian.cpp contained the code that defined the Gaussian class. The main.cpp used the Gaussian class.
The main.cpp file had three parts:
a header, which is where the #include statements were
a class declaration
a main function.
Class Declaration
Then comes the class declaration. The class declaration is very similar to function declarations, which you learned about previously. In fact, as you'll see later in the lesson, you can put the class declaration into a separate .h file just like you did with function declarations.
The purpose of the class declaration is to give the main function access to the Gaussian class.
Notice that a class declaration looks a lot like the variable declarations and function declarations you've already been using. Declarations tell the program what the variable types will be. The declarations also show the input and output types for functions.
Main Function
And finally comes the main function. The main function instantiates objects of the Gaussian class. So the main function uses the class whereas gaussian.cpp defined the class. You could take the code in gaussian.cpp and put it at the bottom of main.cpp; however, your code files will become quite large and hard to read through.
main.cpp
#include <iostream>
// class declaration
class Gaussian
{
private:
float mu, sigma2;
public:
// constructor functions
Gaussian ();
Gaussian (float, float);
// change value of average and standard deviation
void setMu(float);
void setSigma2(float);
// output value of average and standard deviation
float getMu();
float getSigma2();
// functions to evaluate
float evaluate (float);
Gaussian mul (Gaussian);
Gaussian add (Gaussian);
};
int main ()
{
Gaussian mygaussian(30.0,100.0);
Gaussian othergaussian(10.0,25.0);
std::cout << "average " << mygaussian.getMu() << std::endl;
std::cout << "evaluation " << mygaussian.evaluate(15.0) << std::endl;
std::cout << "mul results variance " << mygaussian.mul(othergaussian).getSigma2() << std::endl;
std::cout << "mul results average " << mygaussian.mul(othergaussian).getMu() << std::endl;
std::cout << "add results variance " << mygaussian.add(othergaussian).getSigma2() << std::endl;
std::cout << "add results average " << mygaussian.add(othergaussian).getMu() << std::endl;
return 0;
}
Gaussian.cpp
If you look back at the gaussian.cpp class file, you'll notice that there were four distinct sections. The file contained: