gpt4 book ai didi

c++ - 可以取消引用函数指针吗

转载 作者:行者123 更新时间:2023-12-03 20:23:02 25 4
gpt4 key购买 nike

摘自 E Balagurusamy 的 C++ 面向对象编程

Using function pointers, we can allow a C++ program to select a function dynamically at run time. We can also pass a function as an argument to another function. Here, the function is passed as pointer. The function pointer cannot be de referenced. C++ also allows us to compare two function pointers.


这里写到函数指针不能被取消引用。但是下面的程序运行成功。
#include<iostream> 
int Multiply(int i, int j) {
return i*j;
}
int main() {
int (*p)(int , int);
p = &Multiply;
int c = p(4,5);
int d = (*p)(4,11);
std::cout<<c<<" "<<d;
return 0;
}
在最后一行的第 4 行,我引用了指针。这是正确的吗?它没有给出任何编译器时间错误,最后第四行写的内容与最后第五行写的内容相同吗?我已经开始学习 C++,所以请不要介意我问了一些非常愚蠢的问题。

最佳答案

你的编译器是对的,书是错的。
但是p(4,5)(*p)(4,5)做同样的事情,所以几乎没有必要取消引用函数指针。

[expr.unary.op]/1

The unary * operator performs indirection: the expression to which it is applied shall be a pointer to an object type, or a pointer to a function type ...


(粗体我的)

please don't mind if I have asked something really stupid


不,在验证您阅读的内容方面做得很好。

关于c++ - 可以取消引用函数指针吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67354793/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com