非成员函数中使用'this'的方式无效

14

我一开始把所有的代码都写在同一个.cpp文件里,后来发现这个类变得越来越大,于是我决定把它分成.h和.cpp两个文件。

gaussian.h文件:

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

高斯.cpp文件:

#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个回答

30

你忘记将absoluteDifference声明为Gaussian类的一部分。

更改为:

double absoluteDifference (Gaussian aux){

转变为这样:

double Gaussian::absoluteDifference (Gaussian aux){

顺带一提:最好是通过引用传递而不是值传递:

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

1
啊!我简直不敢相信我没能看到它!我已经看了那么多遍了……谢谢你!! - coconut

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接