【问题标题】:"Candidate function not viable" from g++/gcc compiler. What is wrong here?g++/gcc 编译器的“候选函数不可行”。这里有什么问题?
【发布时间】:2013-12-03 06:51:54
【问题描述】:

我正在尝试编译我的 main.cpp,但我在两个小时内一直收到此错误。这里的问题是将函数作为参数传递,但我认为我做错了什么。编译器说它找不到函数,但我已经在“functions.h”中包含了“newt_rhap(params)”。

我做了 returnType (*functionName)(paramType),但我可能在这里跳过了一些东西。我朋友的代码不需要最近提到的语法。这里有什么问题?

我尝试同时使用 -std=c++11 和 -std=c++98。 gcc/g++ 编译器来自我的 Xcode 命令行工具。

g++ (or gcc) -std=c++98(or 11) main.cpp -o main.out

错误没有区别。

**error: no matching function for call to 'newt_rhap'**

./functions.h:5:8: note: candidate function not viable: no known conversion from 'double' to
      'double (*)(double)' for 1st argument

double newt_rhap(double deriv(double), double eq(double), double guess);

这里是代码。

// main.cpp
#include <cmath>
#include <cstdlib>
#include <iostream>
#include "functions.h"

using namespace std;


// function declarations
// =============
// void test(double d);
// =============

int main(int argc, char const *argv[])
{
    //
    // stuff here excluded for brevity
    //

    // =============
    do
    {
        // line with error
        guess = newt_rhap(eq1(guess),d1(guess),guess);

        // more brevity

    } while(nSig <= min_nSig);
    // =============

    cout << "Root found: " << guess << endl;

    return 0;
}

然后分别是functions.h和functions.cpp

// functions.h
#ifndef FUNCTIONS_H_INCLUDED
#define FUNCTIONS_H_INCLUDED

// ===========
double newt_rhap(double deriv(double), double eq(double), double guess);
// ===========


// ===========
double eq1(double x);
double d1(double x);
// ===========


#endif

// functions.cpp
#include <cmath>
#include "functions.h"

using namespace std;

// ===========
double newt_rhap(double (*eq)(double ) , double (*deriv)(double ), double guess)
{
    return guess - (eq(guess)/deriv(guess));
}
// ===========

// ===========
double eq1(double x)
{
    return exp(-x) - x;
}

double d1(double x)
{
    return -exp(-x) - 1;
}

【问题讨论】:

    标签: c++ gcc g++


    【解决方案1】:

    代替:

    guess = newt_rhap(eq1(guess),d1(guess),guess);
    

    尝试:

    guess = newt_rhap(eq1, d1, guess);
    

    该函数接受两个函数和一个猜测作为参数。通过传递eq1(guess),您传递的是双精度,而不是函数(eq1 的评估结果,参数为 guess

    【讨论】:

    • 澄清一下:这是否意味着我必须在实现本身中为传递的函数指定参数?
    【解决方案2】:

    您在functions.h 中的函数原型的签名与您在functions.cpp 中实现的函数的签名不匹配。

    【讨论】:

    • 我复制了旧版本。最新的在functions.h签名之后。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多