C++函数重载、运算符重载

目录

1、函数重载

2、运算符重载

一元运算符重载

二元运算符重载

关系运算符重载


1、函数重载

重载函数实现相似的功能

重载函数至少要在参数个数、类型、顺序上有所不同


在两个整形中取最大值

int MaxInt(int x,int y){
if(x>y)
return x;
else
return y;
}

在两个字符中取最大值

char MaxChar(char first,char second){
if(first>second)
return first;
else
return second;
}

这两个函数功能类似,调用时程序员需要记住这些函数的名字,加重记忆负担。

如果能用同一个函数名不同类型上做相类似的操作就会方便很多,这种情况即为函数重载:

int myMax(int x,int y){
if(x>y)
return x;
else
return
y
}


char myMax(char first,char second){
if(first>second)
return first;
else
return second;
}

2、运算符重载

一元运算符重载

下面重载负运算符(-)

实现对结构体point的横纵坐标取负

#include<iostream>
using namespace std;
struct point{
double x;
double y;
point(){}
point(double a,double b):x(a),y(b){}
};

//重载-运算符,实现对结构体的成员x和y取负
point operator-(point &a){
point b;
b.x=-a.x;
b.y=-a.y;
return point(b.x,b.y);
}

int main(){
point A(1.2,3.5);
cout<<"A=("<<A.x<<","<<A.y<<")"<<endl;
point B=-A;
cout<<"B=("<<B.x<<","<<B.y<<")"<<endl;
return 0;
}
运行结果
A=(1.2,3.5)
B=(-1.2,-3.5)

二元运算符重载

下面重载除运算符(/)

实现对point结构体的x和y同做除运算

#include<iostream>
using namespace std;
struct point{
double x;
double y;
point(){}
point(double a,double b):x(a),y(b){}
};

//重载\运算符,实现对结构体的成员x和y同做除法 
point operator/(point a,double m){
point b;
b.x=a.x/m;
b.y=a.y/m;
return b;
}

int main(){
point A(1.2,3.5);
cout<<"A=("<<A.x<<","<<A.y<<")"<<endl;
point B=A/2;
cout<<"B=("<<B.x<<","<<B.y<<")"<<endl;
return 0;
}
运行结果
A=(1.2,3.5)
B=(0.6,1.75)

关系运算符重载

下面重载<

实现根据point到原点的距离比较大小

#include<iostream>
using namespace std;
struct point{
double x;
double y;
point(){}
point(double a,double b):x(a),y(b){}
};

//重载<运算符,实现根据点到原点的距离比较大小 
bool operator<(point &a,point &b){
return a.x*a.x+a.y*a.y<b.x*b.x+b.y*b.y;
}

int main(){
point A(1.2,3.5);
cout<<"A=("<<A.x<<","<<A.y<<")"<<endl;
point B(2,4);
cout<<"B=("<<B.x<<","<<B.y<<")"<<endl;
cout<<(B<A)<<endl;
return 0;
}

参考链接

猜你喜欢

转载自blog.csdn.net/Seattle_night/article/details/127344857