3

我试图在我的主程序中调用一个以函数作为参数的类函数,并将该函数应用于私有列表。我收到错误消息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
}
}

这是应用成员函数

void LineEditor::apply(char (*f)(char c))
{
*it=f(c);
}

此外,如果不是很明显,我尝试使用 cctypes toupper 和 tolower,但它们采用并返回整数。

4

4 回答 4

2

当您调用 时ToUpper,它不会返回函数,而是以大写形式返回(假定的)字符。

这不起作用的另一个原因是您无法在函数指针的签名中创建参数。参数区域仅指定函数采用的类型。这个...

char (*f)(char c);
//        ^^^^^^

因此是错误的。

解决方案:

将 astd::functionstd::bind它用于参数:

#include <functional>

line.apply(std::bind(ToUpper, c));

它需要将签名apply更改为:

void LineEditor::apply(std::function<char (char)> f);

如果你不能这样做,你可以简单地让apply第二个参数作为参数:

void LineEditor::apply(char (*f)(char), char c);

并将其称为apply(ToUpper, c).

于 2013-11-03T23:25:38.363 回答
0

您无需重新发明轮子。 ::toupper::tolowertake 和 return int,但它们的有效范围是unsigned char. 此外,std::toupper两者std::tolower都取char.

由于您似乎没有使用std::string,因此我将尝试使其尽可能接近您的代码:

void upperList(LineEditor line)
{
    char c;
    // you do not have a begin() function??
    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();
        c = std::toupper(c);
        line.at() = c; // assuming this returns a reference
        line.right(); 
    }
}

如果您将字符串类修改为更像该类,它会变得更加容易std::string

std::string line;
std::transform(line.begin(), line.end(), line.begin(), std::ptr_fun<int, int>(std::toupper));

例子

于 2013-11-03T23:50:27.810 回答
0

表达式 ToUpper(c) 的类型是 char。所以打电话

line.apply(ToUpper(c));

表示使用 char 类型的参数调用函数 apply。

您应该将函数定义为

void LineEditor::apply( char c, char f(char) )
{
*it=f(c);
}
于 2013-11-03T23:29:47.767 回答
0

表达式ToUpper(c)调用函数,但在调用时apply您不想立即调用该函数,因此您需要 say apply(ToUpper),因为ToUpper这是访问函数本身的方式。

于 2013-11-03T23:25:52.790 回答