operator int()是什么?

中才德创 2009-05-30 10:40:36
// VC2008 debug
#include <iostream>

using namespace std;

class mumble
{
public:
operator int() // 问题在此
{
cout << "mumble::operator int() is called." << endl;
return 0;
}
};

int _tmain(int argc, _TCHAR* argv[])
{
mumble m;
m.operator int();

return 0;
}
...全文
1421 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
青蛙果果 2009-05-30
  • 打赏
  • 举报
回复
重载吧 用来转换
papaofdoudou 2009-05-30
  • 打赏
  • 举报
回复 4
编译器暗中调用了operator int()将一个类对象转换为一个int型,这类函数有一个特点,就是以:
operator+类型+()作为函数签名,没有返回值,实际上 类型名就是返回值。
operator char*()
operator int*()
operator double()
...........
pengzhixi 2009-05-30
  • 打赏
  • 举报
回复
你这个显示调用了这个函数,你函数里面有这个输出语句,它肯定要执行的啊.
papaofdoudou 2009-05-30
  • 打赏
  • 举报
回复
对于你这个定义来说,你可以吧mumble类对象当成一个0来使用。
cout<<m<<endl; 并且随之输出一行“mumble::operator int() is called.”
rabbii 2009-05-30
  • 打赏
  • 举报
回复
int a=m.operator int();
cout<<a<<endl;
这样也会输出"mumble::operator int() is called."是为什么???
a关联上类了?这是那部分的内容?主要有什么作用?
zgjxwl 2009-05-30
  • 打赏
  • 举报
回复
就是重载强制类型转换操作符。。。
http://blog.csdn.net/ljx0305/archive/2009/04/09/4060090.aspx
「已注销」 2009-05-30
  • 打赏
  • 举报
回复
强制类型转换
pengzhixi 2009-05-30
  • 打赏
  • 举报
回复
int a=m.operator int();你可以这么用.
pengzhixi 2009-05-30
  • 打赏
  • 举报
回复
operator int()是转型操作符,目的是把mumble类型的对象转换成int型

65,211

社区成员

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

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