最后一行我一直得到的错误,未解决的外部。
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;
}如果我将原型更改为
int convert(string roman, int i);
int toDecimal(string, bool* (*function)(string));最后一行
cout << roman << " is equal to " << toDecimal(roman, *checker(roman)) << endl;我得到了
“错误2错误C2664:'toDecimal‘:无法将参数2从'bool’转换为'bool *(__cdecl *)(std::string)'”
和
操作数(*)必须是指针
发布于 2013-07-19 23:14:37
如下所示,应该使用指向函数的指针:
bool (*pToFunc) (string) = checker;这意味着pToFunc是一个指向函数的指针,该函数返回bool并获取字符串作为参数,并指向checker。
现在以这样的方式将这个指针发送到您的函数:
cout << roman << " is equal to " << toDecimal(roman, pToFunc) << endl;不要忘记您必须实现检查器
但是,您是用C++编写的,并且有一个更好的方法来实现您想要的目标。它可以是函子。
您应该这样做,使用函子:
定义函子:
class romanFunctor {
public:
bool operator()(string roman) {\\ checker implementetion}
};示例如何使用:
romanFunctor checker ;
string roman;
cin >> roman;
if (checker(roman) == true) {...}发布于 2013-07-19 23:29:09
你在这里有个问题:
int toDecimal(string, bool (function)(string));您将function声明为函数类型的参数。但是函数不能通过值传递(如何创建函数的副本)。相反,您需要接受指向函数的指针。
int toDecimal(string, bool (*fnptr)(string));只有一个*,在参数名称旁边。返回类型仍然是bool,而不是bool*。
然后,您需要传递一个指向函数的指针。这是错误的:
toDecimal(roman, *checker)要创建指针,可以使用&获取地址,稍后使用*取消引用。函数在这方面没有太大不同,只是函数和函数指针之间的转换在某些情况下是隐式的。我更喜欢直截了当。因此,这一呼吁应该是:
toDecimal(roman, &checker)https://stackoverflow.com/questions/17756760
复制相似问题