[英]Invalid use of 'this' in non-member function
I had working on a class and started writing everything in the same .cpp file. 我曾经在一个类上工作并开始在同一个.cpp文件中编写所有内容。 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.
但是,过了一段时间我可以看到这个类越来越大,所以我决定把它分成.h和.cpp文件。
gaussian.h file: 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);
};
gaussian.cpp file: 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;
}
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.
我在fromPrecisionMean函数中使用它并编译。 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. 你忘了将
absoluteDifference
声明为Gaussian
类的一部分。
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){
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.