operator int()用法(转)

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 == 2
i = I;    // I is converted to an int using `operator int()`, returning 2.

--------------------- 
作者:ranqy374 
来源:CSDN 
原文:https://blog.csdn.net/hr10707020217/article/details/13171143 
版权声明:本文为博主原创文章,转载请附上博文链接!

猜你喜欢

转载自blog.csdn.net/dragoo1/article/details/85101969