有意思,重载函数的同名不同址

cxjddd 2003-06-08 02:16:59
很简单的重载:
void f() {}
void f(int) {}
这样f就有两个地址了,这个相当有意思。你看,她不是同时有两个值了吗?这样就要求从上下文中才可以看出到底是哪个f。

void (*fp1)();
那么:fp1 = f;是可以的。因为编译器会找到 void f();。
现在如果我想让fp1得到void f(int);的地址呢?我想到了这样,相当“长”:
fp1 = reinterpret_cast<void(*)()>(static_cast<void(*)(int)>(f));
先用static_cast把f的void(*)(int)的语义带出来,然后就可以用reinterpret_cast转换成void(*)()了。

所以,对重载的函数,可以用static_cast引出特定的语义,也就是选择特定的函数地址。

下面是程序,Dev-C++4.9.8.0通过:
#include <iostream>
#include <cstdlib>
using namespace std;
void f() { int i; i = 1;}
void f(int) { int i; i = 1;}

int main ()
{
cout << "f() is " << (long)static_cast<void(*)()>(f) << endl;
cout << "f(int) is " << (long)static_cast<void(*)(int)>(f) << endl;
void (*fp1)();
void (*fp2)(int);
fp1=f;
cout << "fp1=f is " << (long)fp1 << endl;
fp2=f;
cout << "fp2=f is " << (long)fp2 << endl;

// Error: fp1=reinterpret_cast<void(*)()>(f);
fp1=reinterpret_cast<void(*)()>(static_cast<void(*)(int)>(f));
cout << "fp1=f(int) is " << (long)fp1 << endl;
system ("Pause");
return 0;
}
结果:
f() is 4199040
f(int) is 4199056
fp1=f is 4199040
fp2=f is 4199056
fp1=f(int) is 4199056
...全文
43 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
cxjddd 2003-06-11
  • 打赏
  • 举报
回复
谢谢。对你有用就好,up就不用了。
thrillers 2003-06-09
  • 打赏
  • 举报
回复
学习中。。。。
帮你up
cxjddd 2003-06-08
  • 打赏
  • 举报
回复
GCC里的cout输出函数地址时好象都是一个1。一定要转成整型才能看出地址是不同的。
cxjddd 2003-06-08
  • 打赏
  • 举报
回复
to Zark:

你写的应该是对的。你这样写要简单、好看。
Zark 2003-06-08
  • 打赏
  • 举报
回复
的确是难懂,好像楼主不是在问题,而是在揭示一个答案.
不过reinterpret_cast<void(*)()>(static_cast<void(*)(int)>(f));
也太难懂了.

这样是不是也行?

void f() {}
void f(int) {}

typedef void (*LPF)();
typedef void (*LPF_INT)(int);

void main()
{
LPF lp=f;
LPF_INT lp_int=f;
lp=(LPF)lp_int;
}

(以上程序未经测试,使用者后果自负)
baoyan82505 2003-06-08
  • 打赏
  • 举报
回复
我太菜,没看懂……
snipersu 2003-06-08
  • 打赏
  • 举报
回复
up
i_jianyong 2003-06-08
  • 打赏
  • 举报
回复
up
cxjddd 2003-06-08
  • 打赏
  • 举报
回复
以前看C++时,记了很多问题,昨天整理了一下,放到网上,让大家看看。这个问题也在里面有。
http://tinybaby.y365.com/BenBear/BenCPPQuestions.xml

69,369

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧