Неправильное использование 'this' в функции, не являющейся членом - PullRequest
11 голосов
/ 28 января 2012

Я работал над классом и начал писать все в одном файле .cpp.Однако через некоторое время я увидел, что класс становится все больше и больше, поэтому я решил разделить его на файлы .h и .cpp.

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;
}

Однако я не могу заставить это скомпилировать.Я пытаюсь запустить:

g++ -I. -c -w gaussian.cpp

Но я получаю:

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

Почему я не могу использовать это ??Я использую его в функции fromPrecisionMean, и она компилируется.Это потому, что эта функция возвращает гауссов?Будем очень благодарны за любые дополнительные объяснения, я стараюсь узнать как можно больше!Спасибо!

1 Ответ

26 голосов
/ 28 января 2012

Вы забыли объявить absoluteDifference как часть класса Gaussian.

Изменить:

double absoluteDifference (Gaussian aux){

на это:

double Gaussian::absoluteDifference (Gaussian aux){

Примечание для стороны: Возможно, лучше передать по ссылке, а не по значению:

double Gaussian::absoluteDifference (const Gaussian &aux){
...