main()中的错误来自派生类C ++的函数调用

时间:2014-12-18 10:21:54

标签: c++

//Newton-Raphson Method:

#include <iostream>
#include <cmath>

using namespace std;

class ClassNewton {
    public: 
    double NewtonRaphson(double x0, double epsilon, double f(double), double df(double));
    virtual double f(double) = 0; 
    virtual double df(double) = 0;  
};

double ClassNewton::NewtonRaphson(double x0, double epsilon, double f(double), double df(double)){
        double xold = x0;
        double diff;
        double xnew;
    do {
        xnew = xold - (f(xold)/df(xold));
        xold = xnew;
        } while (abs(diff) > epsilon); 
        return xnew;
}               

class derivedClass:public ClassNewton{
    public:
    double f(double x){ 
    double function = (x * x) + (2 * x) + 2;
    return function;
    }

    double df(double x){
    double derivative = (2 * x) + 2;
    return derivative;
    }
};

int main() {
    derivedClass n;
    double root;
    double x0 = 1.0;
    double epsilon = 0.00001;
    root = n.NewtonRaphson(x0, epsilon, f(root), df(root));
    cout << "The root of the function is  " << root << endl;
    return 0;
}

我使用空的main检查了代码到主函数,它可以编译没有错误。但是,当我集成main时,我收到以下错误:

NewtonRaphson.cc: In function ‘int main()’:
NewtonRaphson.cc:52:44: error: ‘f’ was not declared in this scope
NewtonRaphson.cc:52:54: error: ‘df’ was not declared in this scope
NewtonRaphson.cc:53:47: error: expected ‘;’ before ‘)’ token

我很感激一些解释,我怀疑我是以错误的方式使用虚函数。

1 个答案:

答案 0 :(得分:3)

首先在本声明中

cout << "The root of the function is  ", root);
                                       ^^^^ ^^^

表达无效。

对于其他错误,您必须使用一个对象名来调用类的非静态成员函数。

例如

n.f(root)

n.df(root)

考虑到这个声明

double NewtonRaphson(double x0, double epsilon, double f(double), double df(double));

无效,因为您将使用非静态成员函数fdf作为参数,而相应的参数被声明为非成员函数。

无需定义函数的这两个参数,因为您可以在NewtonRaphson的主体中调用这些成员函数。