C ++成员函数使用另一个成员函数

时间:2013-06-22 09:24:08

标签: c++ class oop member

我正面临一个大问题,我一直试图解决这个问题3天。我有一个CDS类,其中intensity_func成员函数和big_gamma成员函数基本上是成员intensity_func函数的组成部分。

#include <vector>
#include <cmath>

using namespace std   

class CDS
{
public:
    CDS(); 
    CDS(double notional, vector<double> pay_times, vector<double> intensity);
    ~CDS(); 


 double m_notional; 
 vector<double> m_paytimes;
 vector<double> m_intensity;

 double intensity_func(double);

 double big_gamma(double);

};

这是CDS.cpp,其中包含intensity_func成员函数的定义:

#include <vector>
#include <random>
#include <cmath>

#include "CDS.h"

double CDS::intensity_func(double t)
{
    vector<double> x = this->m_intensity;
    vector<double> y = this->m_paytimes;
    if(t >= y.back() || t< y.front())
    {
        return 0;
    }

    else
    {
        int d=index_beta(y, t) - 1;
        double result = x.at(d) + (x.at(d+1) - x.at(d))*(t - y.at(d))/ (y.at(d+1) - y.at(d));
        return result;
    }

我在另一个源文件中实现了一个函数来集成函数和index_beta成员函数中使用的intensity_func函数(使用Simpson规则)。这是代码:

double simple_integration ( double (*fct)(double),double a, double b) 
{
       //Compute the integral of a (continuous) function on [a;b]
       //Simpson's rule is used
       return (b-a)*(fct(a)+fct(b)+4*fct((a+b)/2))/6;
};


double integration(double (*fct)(double),double a, double b, double N) 
{
       //The integral is computed using the simple_integration function
       double sum = 0;
       double h = (b-a)/N;
       for(double x = a; x<b ; x = x+h) {
             sum += simple_integration(fct,x,x+h);
       }
       return sum;
};

int index_beta(vector<double> x, double tau)
{
    // The vector x is sorted in increasing order and tau is a double


    if(tau < x.back())
    {
        vector<double>::iterator it = x.begin();
        int n=0;

        while (*it < tau)
        {
            ++ it;
            ++n; // or n++;
        }
        return n;
    }

    else
    {
        return x.size();
    }


};

所以,我想在我的CDS.cpp中定义big_gamma成员函数是:

double CDS::big_gamma(double t)
{
    return  integration(this->intensity, 0, t);
};

但显然,它不起作用,我收到以下错误消息:reference to non static member function must be called。然后我尝试将intensity成员函数转换为静态函数,但出现了新问题:我不能再使用this->m_intensitythis->m_paytimes了,因为我收到以下错误消息: Invalid use of this outside a non-static member function

1 个答案:

答案 0 :(得分:4)

double (*fct)(double)声明一个类型为“指向函数的指针”的参数。您需要将其声明为“指向成员指针的函数”:double (CDS::*fct)(double)。此外,您需要一个对象,您可以在其上调用指向成员的指针:

(someObject->*fct)(someDouble);