[英]function pointer parameter with type alias
我正在尝试书中的一些示例(lippman撰写的C ++入门),并且正在尝试学习函数指针
此代码:
#include <iostream>
void useBigger (const std::string &s1, const std::string &s2,
bool (*func)(const std::string &, const std::string &))
{
bool valid = func (s1, s2);
std::cout << __func__ << " is called "
<< valid <<std::endl;
}
bool lengthCompare (const std::string &s1, const std::string &s2)
{
if (s1.size() > s2.size())
return true;
else
return false;
}
int main()
{
useBigger ("hello", "sample", lengthCompare);
return 0;
}
这段代码运行正常,但是当我尝试使用诸如typedef之类的类型别名时
#include <iostream>
typedef bool func (const std::string &, const std::string &); /// or typedef bool (*func)(const std::string &, const std::string);
void useBigger (const std::string &s1, const std::string &s2,
func)
{
bool valid = func (s1, s2);
std::cout << __func__ << " is called "
<< valid <<std::endl;
}
bool lengthCompare (const std::string &s1, const std::string &s2)
{
if (s1.size() > s2.size())
return true;
else
return false;
}
int main()
{
useBigger ("hello", "hiiiii", lengthCompare);
return 0;
}
它会产生如下错误:
error: expression list treated as compound expression in functional cast [-fpermissive]
符号func
是类型别名 ,但是您可以将其用作函数。 您实际上需要声明一个参数变量并使用它而不是类型,例如
void useBigger (const std::string &s1, const std::string &s2,
func f)
{
bool valid = f (s1, s2);
std::cout << __func__ << " is called "
<< valid <<std::endl;
}
您的类型定义需要更正如下:
从
typedef bool func (const std::string &, const std::string);
至
typedef bool func (const std::string &, const std::string&);
在useBigger函数中,您必须传递带有变量名称的函数类型,并需要按如下所示更正函数定义:
void useBigger (const std::string &s1, const std::string &s2,
func f)
{
bool valid = f (s1, s2);
std::cout << __func__ << " is called "
<< valid <<std::endl;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.