我在上课时开始在同一个 .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/