首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Visual C++ -以函数为参数的函数调用:更改导致未解析的外部

Visual C++ -以函数为参数的函数调用:更改导致未解析的外部
EN

Stack Overflow用户
提问于 2013-07-19 22:57:54
回答 2查看 176关注 0票数 1

最后一行我一直得到的错误,未解决的外部。

代码语言:javascript
复制
bool checker(string roman);
// Adds each value of the roman numeral together
int toDecimal(string, bool (function)(string));
int convert(string roman, int i);

int main(){
    string roman;
    cout << "This program takes a roman numeral the user enters then converts it to decimal notation." << endl;
    cout << "Enter a roman numeral: ";
    cin >> roman;
    transform(roman.begin(), roman.end(), roman.begin(), toupper);
    cout << roman << " is equal to " << toDecimal(roman,  *checker) << endl;
}

如果我将原型更改为

代码语言:javascript
复制
int convert(string roman, int i);
int toDecimal(string, bool* (*function)(string));

最后一行

代码语言:javascript
复制
cout << roman << " is equal to " << toDecimal(roman, *checker(roman)) << endl;

我得到了

“错误2错误C2664:'toDecimal‘:无法将参数2从'bool’转换为'bool *(__cdecl *)(std::string)'”

操作数(*)必须是指针

EN

回答 2

Stack Overflow用户

发布于 2013-07-19 23:14:37

如下所示,应该使用指向函数的指针:

代码语言:javascript
复制
bool (*pToFunc) (string) = checker;

这意味着pToFunc是一个指向函数的指针,该函数返回bool并获取字符串作为参数,并指向checker

现在以这样的方式将这个指针发送到您的函数:

代码语言:javascript
复制
cout << roman << " is equal to " << toDecimal(roman,  pToFunc) << endl;

不要忘记您必须实现检查器

但是,您是用C++编写的,并且有一个更好的方法来实现您想要的目标。它可以是函子。

您应该这样做,使用函子:

定义函子:

代码语言:javascript
复制
class romanFunctor {
   public:
     bool operator()(string roman) {\\ checker implementetion}
};

示例如何使用:

代码语言:javascript
复制
romanFunctor checker ;
string roman;
cin >> roman;
if (checker(roman) == true) {...}
票数 1
EN

Stack Overflow用户

发布于 2013-07-19 23:29:09

你在这里有个问题:

代码语言:javascript
复制
int toDecimal(string, bool (function)(string));

您将function声明为函数类型的参数。但是函数不能通过值传递(如何创建函数的副本)。相反,您需要接受指向函数的指针。

代码语言:javascript
复制
int toDecimal(string, bool (*fnptr)(string));

只有一个*,在参数名称旁边。返回类型仍然是bool,而不是bool*

然后,您需要传递一个指向函数的指针。这是错误的:

代码语言:javascript
复制
toDecimal(roman,  *checker)

要创建指针,可以使用&获取地址,稍后使用*取消引用。函数在这方面没有太大不同,只是函数和函数指针之间的转换在某些情况下是隐式的。我更喜欢直截了当。因此,这一呼吁应该是:

代码语言:javascript
复制
toDecimal(roman, &checker)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17756760

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档