CPP中操作符operator的俩种作用

在CPP中,一个类的操作符有俩个作用。

  • 第一是对这个类的对象进行操作,如比较,赋值,位移等;
  • 第二是对这个类的对象进行隐式转换

一个例子的代码:

#include <iostream>
using namespace std;

struct struct_a{
  int ta; 
  int tb; 
};

class A
{
  public:
    A(int a) :_a(a) {cout<<"constructor"<<endl;}
  
    // 1: operation
    bool operator > (A aparam)
    {
      cout << "operator >" << endl;
      return _a > aparam._a;
    }
    
    // 2: implicitly conversion
    operator bool()
    {
      cout << "operator bool" << endl;
      return _a;
    }
    
    operator struct_a () 
    {
      struct_a tobj;
      tobj.ta = _a;
      cout<<"operator ttt"<<endl;
      return tobj;
    }
    
  public:
    int _a;
};  
    
int main()
{   
  A a(2);
  A b(10);
    
  cout<<"a>b ? : "<< (a>b) <<endl;
  cout<<"b._a : "<<b._a<<"  b : "<<b<<endl;
    
  struct_a aStruct = a;
  cout<<"aStruct.ta : "<<aStruct.ta<<endl;
    
  return 0;
}

这段代码的运行结果是:

constructor
constructor
operator >
a>b ? : 0
operator bool
b._a : 10  b : 1
operator ttt
aStruct.ta : 2

在比较a>b时,就是调用的operator >, 返回的是bool值True或者False, 这就是对a和b进行比较操作,比较的对象是a和b中的公有变量_a, 具体操作可以通过更改> operator 改变。

在用cout把b的对象输出时, 会调用operator bool(), 把对象b转成bool类型了。

struct_a   aStruct = a 时,调用operator struct_a, 把类A的对象a隐式的转为struct tobj, 并且赋值给aStruct。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值