在非成员函数中使用“this”无效 [英] Invalid use of 'this' in non-member function

查看:2692
本文介绍了在非成员函数中使用“this”无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个类上工作,并开始写同一个.cpp文件中的一切。然而,一段时间后,我可以看到类越来越大,所以我决定将它分为.h和.cpp文件。

I had working on a class and started writing everything in the same .cpp file. 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.

gaussian.h档案:

gaussian.h file:

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文件:

gaussian.cpp file:

#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

但我得到:

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函数和编译。是因为该函数返回高斯吗?任何额外的解释将真正感谢,我尽量多学习尽可能多!谢谢!

Why can't I use this?? I am using it in the fromPrecisionMean function and that compiles. 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!

推荐答案

您忘记了声明 absoluteDifference $ c>高斯类。

You forgot to declare absoluteDifference as part of the Gaussian class.

更改:

double absoluteDifference (Gaussian aux){

到此:

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){

这篇关于在非成员函数中使用“this”无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆