I had working on a class and started writing everything in the same .cpp file. However, after a while I could see the class getting bigger and bigger so I decided to split it into a .h and a .cpp file.
gaussian.h file:
class Gaussian{
private:
double mean;
double standardDeviation;
double variance;
double precision;
double precisionMean;
public:
Gaussian(double, double);
~Gaussian();
double normalizationConstant(double);
Gaussian fromPrecisionMean(double, double);
Gaussian operator * (Gaussian);
double absoluteDifference (Gaussian);
};
gaussian.cpp file:
#include "gaussian.h"
#include <math.h>
#include "constants.h"
#include <stdlib.h>
#include <iostream>
Gaussian::Gaussian(double mean, double standardDeviation){
this->mean = mean;
this->standardDeviation = standardDeviation;
this->variance = sqrt(standardDeviation);
this->precision = 1.0/variance;
this->precisionMean = precision*mean;
}
//Code for the rest of the functions...
double absoluteDifference (Gaussian aux){
double absolute = abs(this->precisionMean - aux.precisionMean);
double square = abs(this->precision - aux.precision);
if (absolute > square)
return absolute;
else
return square;
}
However, I can't get this to compile. I try running:
g++ -I. -c -w gaussian.cpp
But I get:
gaussian.cpp: In function ‘double absoluteDifference(Gaussian)’:
gaussian.cpp:37:27: error: invalid use of ‘this’ in non-member function
gaussian.h:7:16: error: ‘double Gaussian::precisionMean’ is private
gaussian.cpp:37:53: error: within this context
gaussian.cpp:38:25: error: invalid use of ‘this’ in non-member function
gaussian.h:6:16: error: ‘double Gaussian::precision’ is private
gaussian.cpp:38:47: error: within this context
Why can't I use this?? I am using it in the fromPrecisionMean function and that compiles. Is it because that function returns a Gaussian? Any extra explanation will be really appreciated, I am trying to learn as much as I can! Thanks!
You forgot to declare absoluteDifference
as part of the Gaussian
class.
Change:
double absoluteDifference (Gaussian aux){
to this:
double Gaussian::absoluteDifference (Gaussian aux){
Side Note: It might be better to pass by reference rather than by value:
double Gaussian::absoluteDifference (const Gaussian &aux){
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With