提问人:coconut 提问时间:1/29/2012 更新时间:1/29/2012 访问量:49827
在非成员函数中无效使用“this”
Invalid use of 'this' in non-member function
问:
我正在做一个类,并开始在同一个 .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函数中使用它并编译。是因为该函数返回高斯函数吗?任何额外的解释将不胜感激,我正在尽可能多地学习!谢谢!
答:
30赞
Mysticial
1/29/2012
#1
您忘记声明为班级的一部分。absoluteDifference
Gaussian
改变:
double absoluteDifference (Gaussian aux){
对此:
double Gaussian::absoluteDifference (Gaussian aux){
旁注:最好按引用传递,而不是按值传递:
double Gaussian::absoluteDifference (const Gaussian &aux){
评论
1赞
coconut
1/29/2012
啊!我简直不敢相信我看不到它!我经历了很多次......!谢谢!!
评论