c ++的operator的两种用法

operator,它有两种用法,一种是operator overloading(操作符重载),一种是operator casting(操作隐式转换)。


1.operator overloading
C++可通过operator 重载操作符,格式如下:类型T operator 操作符 (),如比重载+,如下所示

[cpp]  view plain  copy
 print ?
  1. template<class T>  
  2. class A  
  3. {  
  4. public:  
  5.     const T operator + (const T& rhs)  
  6.     {  
  7.        return this->m_ + rhs;  
  8.     }  
  9. private:  
  10.     T m_;  
  11. };  

2 operator casting

C++可通过operator 隐式转换,格式如下: operator 类型T (),T是要转换到的类型。如下所示

[cpp]  view plain  copy
 print ?
  1. #include<iostream>  
  2. using namespace std;  
  3. #include <iostream>  
  4. using namespace std;  
  5. #include<iostream>  
  6. using namespace std;  
  7. class MyClass  
  8. {  
  9.     public:  
  10.         MyClass(int b = 0):a(b)  
  11.         {  
  12.         }  
  13.         MyClass(MyClass &temp)  
  14.         {  
  15.         }  
  16.         ~MyClass()  
  17.         {  
  18.         }  
  19.         operator int()//转换运算符,MyClass转换到int类型  
  20.         {  
  21.             cout<<"载入转换运算符函数!"<<endl;  
  22.             return a;  
  23.         }  
  24.     public:  
  25.         int a;  
  26. };  
  27. int main()  
  28. {  
  29.     MyClass obj(100);  
  30.     cout<<(int)obj<<endl;//强转换 与int(obj)相同!
  31.     system("pause");  
  32.     return 0;  
  33. }  
载入转换运算符函数!
100


扩展1:
(A)b与A(b)的区别
(1)
以上代码中
注意: ( int )obj与int(obj)相同 
(int)obj:C风格
int(obj) :C++风格

(2)
此外
class A{};
class B{};
B b;
注意: ( A )b不同于A(b
(A)b;//类型转换  将b对象转为A类型对象 返回A类型的临时对象 调用类型隐式转换函数
Aa = A(b);//其中A(b)创建A类型对象 b作为参数 返回A类型的临时对象 调用构造函数 

扩展2:
A(x)的使用:
a = A(x);实际使用该语句时b可以为左值或右值,上例中x为左值;
A(x);//仅当x为一个右值 可以将此作为一条单独语句(若x为左值,会发生重定义错误


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值