一 operator
一 语法
1 关键字 operator 2 语法 函数返回值类型 operator 要重载的运算符(形参表) { 函数体; }
二 实例
class Mydata{
public:
int num;
Mydata(){}
Mydata(int var) :num(var){}
/*···正负数···*/
Mydata& operator+(){
Mydata temp;
temp.num = +this->num;
return temp;
}
Mydata& operator-(){
Mydata temp;
temp.num = -this->num;
return temp;
}
/*···自增自减···*/
void operator++(){
this->num++;
}
void operator--(){
this->num--;
}
/*···输入输出···*/
friend istream& operator>>(istream& left, Mydata& right);
friend ostream& operator<<(ostream& left, Mydata& right);
/*···加减乘除···*/
Mydata& operator+(const Mydata& var){
Mydata temp;
temp.num = this->num + var.num;
return temp;
}
Mydata& operator-(const Mydata& var){
Mydata temp;
temp.num = this->num - var.num;
return temp;
}
Mydata& operator*(const Mydata& var){
Mydata temp;
temp.num = this->num * var.num;
return temp;
}
Mydata& operator/(const Mydata& var){
Mydata temp;
temp.num = this->num / var.num;
return temp;
}
Mydata& operator%(const Mydata& var){
Mydata temp;
temp.num = this->num % var.num;
return temp;
}
/*···关系运算符···*/
bool operator==(Mydata& var){
if (this->num == var.num)
return 1;
else
return 0;
}
bool operator!=(Mydata& var){
if (this->num != var.num)
return 1;
else
return 0;
}
bool operator>(Mydata& var){
if (this->num > var.num)
return 1;
else
return 0;
}
bool operator<(Mydata& var){
if (this->num < var.num)
return 1;
else
return 0;
}
bool operator>=(Mydata& var){
if (this->num >= var.num)
return 1;
else
return 0;
}
bool operator<=(Mydata& var){
if (this->num <= var.num)
return 1;
else
return 0;
}
/*···逻辑运算符···*/
bool operator&&(Mydata& var){
return this->num&&var.num;
}
bool operator||(Mydata& var){
return this->num||var.num;
}
bool operator!(){
return !this->num;
}
/*···位运算···*/
size_t operator&(Mydata& var){
return this->num&var.num;
}
size_t operator|(Mydata& var){
return this->num | var.num;
}
size_t operator^(Mydata& var){
return this->num^var.num;
}
size_t operator~(){
return ~this->num;
}
};
int main(){
Mydata obj_test1(5);
Mydata obj_test2(9);
obj_test1--;
printf("%o\n", obj_test1^obj_test2);
cout << "obj_test1 = " << obj_test1 << endl;
}
istream& operator>>(istream& left, Mydata& right){
left >> right.num;
return left;
}
ostream& operator<<(ostream& left, Mydata& right){
left << right.num;
return left;
}
三 注意事项
-
只能重载已有的运算符,不能创造新的运算符
-
"." "::" "? :" "sizeof()" 不能重载
-
不能违背惯例
-
参数数量<==>目数
-
作为成员函数重载,this指针占一个参数
二 特殊
<<和>>只能作为友元重载,不能作为成员函数重载