[英]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.