一、运算符重载
对象喝运算符之间的关系。
运算符:
赋值运算符 =
算术运算符 + - * / %
关系运算符 > >= < <= == !=
逻辑运算符 && || !
其他运算符 ++ -- ?:
位运算符 & | ^ ~ << >>
1.对象遇到运算符会有什么表现
证明步骤
设计类 创建对象 对对象进行运算操作
2.运算符重载使用
对于已有的运算符只能对基本数据类型进行操作,没有办法对自定义的数据类型进行操作
如果想让自定义数据类型执行运算操作,需要给运算符赋予新功能,实现数据运算
运算符重载 --- 函数重载
注意事项:
1、运算符的重载必须是已有的运算符,不能随意创造。
2、重载运算符不能改变原有运算符的规则和操作数
3、重载后的功能要和原有的运算符一致,不要没有目的的重载运算符
4、运算符重载最好有无参构造函数,因为在计算的过程中有可能会用到临时对象
5、重载后使用运算符的时候就相当于调用了运算符重载函数 a+b a.operator +(b)
不允许重载的运算符:
成员访问符号:.
成员访问符号:.*
计算内存: sizeof
三目运算符: ?:
限定符: ::
3.运算符重载的实现
成员函数、友元函数,计算的时候一般需要访问数据,在类中数据成员一般是有私有的。
类内定义:
返回值类型 operator 运算符(形参)
{
}
类外定义:
类内声明:返回值类型 operator 运算符(形参);
类外定义:返回值类型 类名:: operator 运算符(形参);
#include<iostream>
using namespace std;
class point
{
private:
int xp;
int yp;
public:
point(){
}
point(int x,int y)
{
xp=x;
yp=y;
}
void show()
{
cout<<"xp:"<<xp<<",yp"<<yp<<endl;
}
point operator +(const point &p1)
{
point c;
c.xp = xp + p1.xp;
c.yp = yp + p1.yp;
return c;
}
};
int main()
{
point a(1,3);
point b(2,5);
point c=a+b; // a.operator+(b)
c.show();
return 0;
}
注意:
运算符的重载使用成员函数实现的:
因为类里面有一个this 指针,指向运算符的左侧操作数,所以重载函数的形参比实际的运算符的新参少一个。
如果是双目运算符 --- 只有一个操作数
如果是前置单目运算符 --- 省略操作数 ++a 先加后用
如果是后置单目运算符 --- 需要写一个整形参数,但是这个参数不用,主要是为了区分前置运算符 a++ --- 先用后加
练习1:== 关系运算符重载 (做两个对象点坐标相等判断)
bool point::operator ==(const point &p)
{
if(xp==p.xp && yp==p.yp)
{
return true;
}
else
{
return false;
}
}
二、友元函数
普通函数做一个类的友元实现运算符的重载。
重载函数的形参和实际的运算符的参数要一致
双目运算符传2个,
单目运算符 -- 可以传可以不传
步骤
1、定义友元函数
返回值类型 operator 运算符(形参)
{
}
2、在类内声明友元
friend 返回值类型 operator 运算符(形参);
例:实现我们point类的 - 的重载
返回值类型:point
函数名:operator -
形参:const point &a,const point &b
point operator -(const point &a,const point &b)
{
point c;
c.xp = a.xp - b.xp;
c.yp = a.yp - b.yp;
return c;
}
point类中:friend point operator -(const point &a,const point &b)
必须要使用友元函数重载的运算符
1、左侧的对象是常量 5 + a // 5.operator+(a)
2、输入输出重载 << >>
例子:友元重载输入输出
#include<iostream>
using namespace std;
class point
{
private:
int xp;
int yp;
public:
point()
{
}
point(int x ,int y)
{
xp = x;
yp = y;
}
friend istream &operator >>(istream &cs,point &a);
friend ostream &operator <<(ostream &ct,const point &b);
void show()
{
cout << "xp:" << xp << ",yp:" << yp << endl;
}
};
istream &operator >>(istream &cs,point &a)
{
cout << "请输入第一个参数:" ;
cs >> a.xp;
cout << "请输入第二个参数:";
cs >> a.yp;
return cs;
}
ostream &operator <<(ostream &ct,const point &b)
{
cout << "第一个参数:" ;
ct << b.xp;
cout << "第二个参数:" ;
ct << b.yp << endl;
return ct;
}
int main()
{
point a,b,c;
cin >> a;
cout << a;
cin >> b >> c;
cout << b << c;
a.show();
b.show();
c.show();
return 0;
}