繁体   English   中英

重载指向函数的指针

[英]Overloaded pointer to function

我正在查看以下代码:

string toUpper(string s) {
    string result;
    int (*toupperp)(int) = &toupper; // toupper is overloaded
    transform(begin(s), end(s), back_inserter(result), toupperp);
    return result;
}

我被这条线弄糊涂了:

int (*toupperp)(int) = &toupper; // toupper is overloaded

为什么这条线路必要?

我相信&从内存中检索指向某事物的指针。 但是toupper ,这个函数的名字已经是指针,不是吗? 为什么我们不能这样做:

int (*toupperp)(int) = toupper;

3.如果在string上使用函数,函数是否重载为int

1)真的没有必要。 如果您已经使用了using namespace std指令,则必须转换为所需的类型,以便让编译器知道您想要的重载 所以,你也可以说

transform(begin(s), end(s), back_inserter(result), static_cast<int(*)(int)>(&toupper));

否则以下内容应该足够了:

transform(begin(s), end(s), back_inserter(result), ::toupper);

2)作为函数名称的标识符会衰减为指针,是的,但它们并不完全相同。 话虽这么说,在这种情况下应该没问题

int (*toupperp)(int) = toupper;

甚至(如果你还没有using namespace std指令):

auto toupperp = toupper; 

3)它与C标准库的兼容性。 它用在s每个元素上, stringchar

你传递给transform是一个指向函数toupper的指针(参见函数指针 )。 将此指针存储到局部变量toupperp toupperp的类型是一个指向函数的指针,该函数将int作为参数并返回int

除非以奇怪的方式定义toupper否则该函数似乎被transform用于将每个输入字符更改为大写。 每个单个字符都作为整数处理(如果需要,可以使用隐式转换)。

关于你的问题2,使用操作&您做出更明确的你正在服用的函数的地址,但你确实可以忽略它。 看到这里 (我今天学到了一些东西)。

如果toupper过载,使用中间变量是获得完全所需过载的安全方法。 如果所需的重载消失,则此方法将在编译时捕获该问题。 看到这里 (这是我今天学到的东西)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM