【发布时间】:2013-11-03 23:21:34
【问题描述】:
我试图在我的主程序中调用一个类函数,该函数将一个函数作为其参数,并将该函数应用于私有列表。我收到错误invalid conversion from char to char (*f)(char)。希望我只是不明白如何将函数作为参数传递。以下是我的主 cpp 文件中的函数
char ToUpper(char c)
{
char b='A';
for(char a='a';a<='z';a++)
{
if(a==c)
{
c=b;
break;
}
++b;
}
return c;
}
void upperList(LineEditor line)
{
char c;
for(int i=0;i<100;i++) //ensure iterator is at beginning of line
line.left();
for(int i=0;i<100;i++)
{
c=line.at(); //assign character current element pointed to by iterator
line.apply(ToUpper(c)); //problem: trying to apply ToUpper function to char c
line.right(); //apply function and increment iterator
}
}
这是apply成员函数
void LineEditor::apply(char (*f)(char c))
{
*it=f(c);
}
另外,如果不是很明显,我尝试使用 cctypes toupper 和 tolower,但它们接受并返回整数。
【问题讨论】:
-
` 我尝试使用 cctypes toupper 和 tolower,但它们接受并返回整数。` char 可以隐式转换为
int,或者您可以使用std::toupper/std::tolower.你的ToUpper版本效率很低。 -
是啊哈哈,上面的代码似乎只是将隐式转换抛到了窗外。尽管我已经很容易地实现了这些,但使用来自答案的代码,谢谢!
标签: c++ function class arguments