Return to the Basic - 运算符重载 (Operator Overloading )

type classname::operator#(arg-list){
 //
}


运算符重载 (Operator Overloading)
运算符重载,就是对已有的运算符重新进行定义,赋予其另一种功能,以适应不同的数据类型。

运算符重载与函数重载是紧密相连的。
可以创建一个operator 函数来定义运算符的行为。通用形式如下:

type 是具体运算返回值的类型。
#代表需要重载的运算符。

使用成员函数重载运算符。

#include <iostream>
using namespace std;

class three_d{
 int x,y,z;
public:
 three_d(){
  x=y=z=0;
 }

 three_d(int i,int j,int k){
  x=i;y=j;z=k;
 }

 three_d operator+(three_d op2);
 three_d operator=(three_d op2);
 void show();
};

//重载+
three_d three_d::operator+(three_d op2){
 three_d temp;
 temp.x=x+op2.x;
 temp.y=y+op2.y;
 temp.z=z+op2.z;
 return temp;
}

//重载= (赋值运算符)
three_d three_d::operator=(three_d op2){
 x=op2.x;
 y=op2.y;
 z=op2.z;
 return *this;
}

//输出x,y,z 值.
void three_d::show(){
 cout<<x<<",";
 cout<<y<<",";
 cout<<z<<"\n";
}

int main(){
 three_d a(1,2,3),b(4,5,6),c;
 a.show();   //将输出 1,2,3
 b.show();   //将输出 4,5,6
 c.show();   //将输出 0,0,0

 c=a+b;    //对象a,b相加
 c.show();   //将输出 5,7,9
 
 c=b=a;    //多重赋值
 c.show();   //将输出 1,2,3
 b.show();   //将输出 1,2,3

 return 0;
}


还可以使用非成员函数和友元函数重载运算符。

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值