c++运算符重载

重载

重载的运算符是具有特殊名字的函数,他们的名字由关键字operator和其后要定义的运算符共同组成。

当一个重载的运算符是成员函数时,this绑定到左侧运算对象。

成员运算符函数的参数数量比运算对象的数量少一个。

重载时使用与内置类型一致的含义。

 

注意&、*和const的使用

输入输出运算符:&opetator>>、 &opetator << 输入输出运算符必须是非成员函数

算术和关系运算符:opetator+、opetator==

赋值运算符:opetator=、opetator+=

下标运算符:opetator[]

递增递减运算符:前置opetator++()、opetator--()。后置opetator++(int)、opetator--(int)

成员访问运算符:&opetator*()const、*opetator->()const

函数调用运算符:opetator()(int val)

 

Data da1 = Data(1, 2, "aaa");

Data da2 = Data(10, 20, "bbb");

da1 = da1 + da2;

da1.Show();

cout << (da1 == da1) << endl;

cout << (da1 != da2) << endl;

 

da1 = da2;

da1.Show();

da1 += da2;

da1.Show();

 

++da1;

da1.Show();

 

da1--;

da1.Show();

 

Data *da3 = new Data(5, 6, "ccc");

da1 = (*da3);

da1.Show();

 

*da3 = da2;

da3->Show();

 

da1();

class Data

{

public:

Data(int x, int y, string str) :x(x), y(y), str(str) {

}

//算术运算符

Data operator+(const Data &da)

{

this->x += da.x;

this->y += da.y;

this->str += da.str;

return *this;

}

//关系运算符

bool operator==(const Data &da)

{

return this->x == da.x &&

this->y == da.y&&

this->str == da.str;

}

bool operator!=(const Data &da)

{

return !(*this == da);

}

//赋值运算符

Data operator=(const Data &da)

{

this->x = da.x;

this->y = da.y;

this->str = da.str;

return *this;

}

//符合赋值运算符

Data operator+=(const Data &da)

{

this->x += da.x;

this->y += da.y;

this->str += da.str;

return *this;

}

//下标运算符

int operator[](int index)

{

int num;

/**/

return num;

}

//递增运算符

//要区分前置和后置,实现区别为后置版本接受一个额外的int类型参数,编译器会自动提供参数。

//前置

Data operator++()

{

++this->x;

++this->y;

return *this;

}

//后置

Data operator--(int)

{

--this->x;

--this->y;

return *this;

}

//成员访问运算符* ->

Data operator*() const

{

return *this;

}

Data *operator->() const

{

return &this->operator*();

}

//函数调用运算符

void operator()()

{

this->Show();

}

void Show()

{

cout << "x=" << x << " y=" << y << " str=" << str << endl;

}

private:

int x;

int y;

string str;

};

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值