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;
}
还可以使用非成员函数和友元函数重载运算符。