operator int()用法

来源:互联网 发布:动态最优化课后题答案 编辑:程序博客网 时间:2024/06/08 18:57

operator int() 是类型转换运算符,比如:


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;     //作用一样}

该函数的返回值类型就是函数名,所以不用显式地表示出。

什么叫返回类型就是函数名?
============================
返回类型是int,函数名也是int,就是说不写成 int operator int() const { return value; },
返回类型被省去了。
operator int() is a conversion operator, which allows this class to be used in place of an int. If an object of this type is used in a place where an int (or other numerical type) is expected, then this code will be used to get a value of the correct type.

For example:

int i(1);INT I(2); // Initialised with constructor; I.a == 2i = I;    // I is converted to an int using `operator int()`, returning 2.