operator int() const { return value; }什么意思?

lululugq 2005-03-02 11:49:53
如题
...全文
825 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
zeusnchen 2005-03-02
  • 打赏
  • 举报
回复
declaration like:
operator type() const{...}
or
operator type() {...}

is a customer defined operator, it is used by compiler to perform implicit conversion when needed. (or you can implictly envoke such operator by (type)classObj or type(classObj) or classObjPtr->operator type() ...

the const keyword tell compiler that this operator will not modify the internal state of the object, so with const keywork, this operator can be used on constant object of this class, otherwise, it can only be used on non-constant objects of this class
dongpy 2005-03-02
  • 打赏
  • 举报
回复
什么叫返回类型就是函数名
============================
返回类型是int,函数名也是int,就是说不写成 int operator int() const { return value; },
返回类型被省去了。

lululugq 2005-03-02
  • 打赏
  • 举报
回复
operator int() const { return value; }
int operator!() const { return !value; }
这两句有关系吗?
lululugq 2005-03-02
  • 打赏
  • 举报
回复
不太明白,这个跟运算符重载有关系吗?
那个operator代表什么?什么叫返回类型就是函数名
dongpy 2005-03-02
  • 打赏
  • 举报
回复
该函数的返回值类型就是函数名,所以不用显式地表示出。
dongpy 2005-03-02
  • 打赏
  • 举报
回复
这是类型转换运算符,给个例子:
struct A
{
int a;
A(int i):a(i){}
operator int() const { return a; }
};

void main()
{
A aa(1);
int i = int(aa);
int j = aa; //作用一样
}
carefulman 2005-03-02
  • 打赏
  • 举报
回复
这是类提供的一个类型转换函数,并且该转换函数为类的CONST成员函数
有了这个后可以这样:
youclass t;
int i =t;

65,210

社区成员

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

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