vc2005中打印成员函数的地址

Tracy2007 2008-02-27 11:04:58

在vc2005里编译运行这个程序,打印类成员函数的地址,结果为什么全是1呢??


#include <iostream>
using namespace std;

class Base
{
public:
void base_fun()
{

}

virtual void vf()
{

}

virtual void vf1()
{

}
};

class Derived : public Base
{
public:
void derived_fun()
{

}

virtual void vf()
{

}

virtual void vf1()
{

}
};

int main(int argc, _TCHAR* argv[])
{
cout << &Base::base_fun << endl;
cout << &Derived::base_fun << endl;
cout << &Derived::derived_fun << endl;
cout << &Base::vf << endl;
cout << &Base::vf1 << endl;
cout << &Derived::vf << endl;
cout << &Derived::vf1 << endl;

return 0;
}


运行结果:
1
1
1
1
1
1
1



...全文
162 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
星羽 2008-02-28
  • 打赏
  • 举报
回复
member function pointer 不是一般的 pointer
taodm 2008-02-28
  • 打赏
  • 举报
回复
继续啊,就差一步了,为啥C++标准规定成员函数指针能转化为bool类型而不是void *类型?
hastings 2008-02-28
  • 打赏
  • 举报
回复
显然,编译器找不到定义时,会试图进行隐式转换,
而成员函数指针能转化为bool类型,而bool类型能打印:
class A
{
public:
void fun()
{
cout<<"A::fun()\n";
}
};
/*
std::ostream& operator<<(std::ostream& os,void(A::* const& mpf)())
{
char str[32];
sprintf(str,"%p",mpf);
return os<<str;
}*/
int main()
{
printf("%p\n",&A::fun);
cout<<std::boolalpha<<&A::fun<<endl;
return 0;
}
hastings 2008-02-28
  • 打赏
  • 举报
回复
以下为推测:
比如要用cout打印数字1,
则必须有下列函数的定义:
std::ostream& operator<<(std::ostream& os,const int& i)
{
//具体实现我不知道
}
然而,
class A
{
public:
void fun()
{
cout<<"A::fun()\n";
}
};
想:cout<<&A::fun;时,之前就必须已经有了下列函数声明:
std::ostream& operator<<(std::ostream& os,void(A::* const& mpf)())
{
//以下为可能的一种实现代码:
char str[32];
sprintf(str,"%p",mpf);
return os<<str;
}
但显然,编译器开发商附带的库函数中,肯定没有关于void(A::*mpf)()的流操作函数声明和定义;
因为他们不肯能知道用户会定义那些类!!!!
class   A 
{
public:
void fun()
{
cout<<"A::fun()\n";
}
};
std::ostream& operator<<(std::ostream& os,void(A::* const& mpf)())
{
char str[32];
sprintf(str,"%p",mpf);
return os<<str;
}
int main()
{
printf("%p\n",&A::fun);
cout<<&A::fun<<endl;
return 0;
}
taodm 2008-02-28
  • 打赏
  • 举报
回复
因为C++标准并不同意“把&Derived::vf1得到的当作是它的地址”这个观点。
自以为聪明往往是大愚若智。
Tracy2007 2008-02-28
  • 打赏
  • 举报
回复

谢谢各位

那位能具体说说cout为什么这么蠢吗?
hastings 2008-02-27
  • 打赏
  • 举报
回复
printf("%p\n", ...)很聪明的。
baihacker 2008-02-27
  • 打赏
  • 举报
回复

#define Print_P(p) printf("%p\n", p)
int main(int argc, _TCHAR* argv[])
{
Print_P(&Base::base_fun);
Print_P(&Derived::base_fun);
Print_P(&Derived::derived_fun);
Print_P(&Base::vf);
Print_P(&Base::vf1);
Print_P(&Derived::vf);
Print_P(&Derived::vf1);

return 0;
}
  • 打赏
  • 举报
回复
前面加上(void*)
sheenl 2008-02-27
  • 打赏
  • 举报
回复
因为cout比较蠢, 改用printf("%p\n", ...)即可。

或者自行强制转换

64,639

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

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