c++ - 在非成员函数中无效使用 'this'

标签 c++ compiler-errors this non-member-functions

我在上课时开始在同一个 .cpp 文件中编写所有内容。然而,过了一会儿,我发现这个类越来越大,所以我决定将它分成一个 .h 和一个 .cpp 文件。

高斯.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 函数中使用它并进行编译。是因为该函数返回高斯分布吗?任何额外的解释将不胜感激,我正在努力学习尽可能多的东西!谢谢!

最佳答案

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

改变:

double absoluteDifference (Gaussian aux){

为此:

double Gaussian::absoluteDifference (Gaussian aux){

旁注:通过引用传递而不是通过值传递可能更好:

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

关于c++ - 在非成员函数中无效使用 'this',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9047671/

相关文章:

c++ - std::vector 不保留在实现中实例化的推回对象

python - 解包十六进制编码的 float

c++ - 没有这样的文件或目录,但文件存在

C: "invalid use of undefined type ‘struct X’ & 取消引用指向不完整类型的指针“错误

c++ - 在类中使用相同的变量可以在构造函数 C++ 中使用吗?

c++ - 为支持 CNAME 记录的 A 记录配置 TTL

java - java自动机的简单枚举

jquery - 淡入 1 个元素

c++ - 这个和*这个区别

c++ - 存在线程错误的 SFML 程序