运算符函数:operator 运算符
运算符重载,两种方式:
a.成为成员函数
b.名字空间函数(友元函数)
不能重载的运算符有: ::, ., .*, ?:
必须重载为成员函数的运算符: [], (), ->, =
要求:
a.不能引进新运算符
b.不改变元数,优先级,结合性。
定义语法:
二元函数
值类型 operatoe◎(类型名 形参名) 函数体 // 成员函数
值类型 operatoe◎(类型名 形参名, 类型名 形参名) 函数体 // 全局函数
一元函数
值类型 operatoe◎() 函数体 // 成员函数
值类型 operatoe◎(类型名 形参名) 函数体 // 全局函数
例子程序:
#include <iostream>
using namespace std;
class com{
private:
int real;
int img;
public:
com(int real = 0, int img = 0){
this->real = real;
this->img = img;
}
void com_add(com &x, com &y, com &z){
z.real = x.real + y.real;
z.img = x.img + y.img;
}
com operator + (com x){
return com(this->real + x.real, this->img + x.img);
}
/*
com operator + (com & x){
return com(this->real + x.real, this->img + x.img);
}
*/
/*
//warning C4172: returning address of local variable or temporary
com & operator + (com & x){
return com(this->real + x.real, this->img + x.img);
}
*/
com operator + (int x){
return com(this->real + x, this->img);
}
friend com operator + (int x, com y);
void show(){
cout << real << "," << img << endl;
}
};
com operator +(int x, com y){
return com(x + y.real, y.img);
}
int main()
{
com a, b(1, 2), c(2, 3);
a = b + c;
a.show();
a.com_add(b, c, a);
a.show();
a = b + 3;
a.show();
a = 3 + c;
a.show();
}
注意:com & operator + (com & x)
在类成员函数中重载运算符是不允许返回引用的,会出现“返回局部变量的地址”警告。
但是对于函数 void com_add(com &x, com &y, com &z)则可以。