c++ - 来自 g++/gcc 编译器的 "Candidate function not viable"。这里有什么问题?

标签 c++ gcc g++

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

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

我尝试同时使用 -std=c++11 和 -std=c++98。 gcc/g++ 编译器来 self 的 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;
}

最佳答案

代替:

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

尝试:

guess = newt_rhap(eq1, d1, guess);

该函数以两个函数和一个猜测作为参数。通过传递 eq1(guess),您传递的是一个 double ,而不是函数(eq1 的计算结果,参数为 guess)

关于c++ - 来自 g++/gcc 编译器的 "Candidate function not viable"。这里有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20344670/

相关文章:

c++ - 帮助插入第一个 BST

c++ - 用整型变量重载类名

c++ - 返回 NaN 还是抛出异常?

c++ - 是否可以用外部友元 lambda 函数覆盖虚函数?

c++ - g++ 编译器不识别嵌套模板类

c++ - 为什么 CLang++ 不优化循环而 G++ 可以?

c++ - 多重分派(dispatch)如何违反 C++ 中的封装

C++ 函数重载、表达式模板和命名空间

c++ - Autotools 和 OpenSSL MD5/RAND_bytes 未定义

c - 从多个线程读取 int 是否安全?