返回信息流一般陈述:函数名是一个地址,函数指针存的是函数的地址吧,那么调用的时候是要加上解引用的吧
写了点测试的代码,发觉不加解引用(/*如下代码的最后两行*/)依旧运行,居然正确,何解?
#include<iostream>
using namespace std;
int add(int, int);
int multiply(int, int);
void main()
{
int (*function[2])(int, int);
int (*p_function)(int, int);
function[0] = add;
function[1] = multiply;
p_function = multiply;
int a = 0;
int b = 0;
cout<<"please enter two integers..."<<endl;
cin>>a>>b;
cout<<"sum of "<<a <<" and " << "b is "<< function[0](a, b)<<endl;
cout<<"the product of "<<a <<" and " << "b is "<< p_function(a,b)<<endl;
cout<<"the product of "<<a <<" and " << "b is "<< (*p_function)(a,b)<<endl;
}
int add(int x, int y)
{
return x + y;
}
int multiply(int x, int y)
{
return x*y;
}
这是一条镜像帖。来源:北邮人论坛 / cpp / #45209同步于 2010/10/24
该镜像源已超过 30 天没有更新,可能在源站已被删除。
CPP机器人发帖
[求助]函数指针的调用
Lenghaijun
2010/10/24镜像同步6 回复
订阅后,新回复会通过你的通知中心匿名送达。
6 条回复
是啊,可是星号(*)是解引用符,为什么会这样呢?
是规定么,一般情况下,指针的内容和指针所指向的内存的内容不一样的,这是怎么回事呢?
【 在 rainblue 的大作中提到: 】
: 一样的。
: --
: 高楼底下有阴影,霓红灯下有血泪!
: ...................
Quote from C++ Primer Plus
[quote]
double pam(int);
double (*pf)(int);
pf = pam; // pf now points to the pam() function
double x = pam(4); // call pam() using the function name
double y = (*pf)(5); // call pam() using the pointer pf
Actually, C++ also allows you to use pf as if it were a function name:
double y = pf(5); // also call pam() using the pointer pf
Using the first form is uglier, but it provides a strong visual reminder that the code is using a function pointer.
History Versus Logic
Holy syntax! How can pf and (*pf) be equivalent? One school of thought maintains that because pf is a pointer to a function, *pf is a function; hence, you should use (*pf)() as a function call. A second school maintains that because the name of a function is a pointer to that function, a pointer to that function should act like the name of a function; hence you should use pf() as a function call. C++ takes the compromise view that both forms are correct, or at least can be allowed, even though they are logically inconsistent with each other. Before you judge that compromise too harshly, reflect that the ability to hold views that are not logically self-consistent is a hallmark of the human mental process
[/quote]
【 在 guo 的大作中提到: 】
: Quote from C++ Primer Plus
: [quote]
: double pam(int);
: ...................
明白了,谢谢哈,牛人浮出来了