一、运算符重载
C++中运算符重载允许将标准运算符运用在自己定义的类的对象,包括对象之间的运算等等。
二、运算符重载的类型
1、成员函数的重载
2、友缘函数的重载
三、运算符重载规则
1、不能有新的运算符
2、运算符重载后自身的优先级以及结合规则不变
3、不能重载运算符有:
作用域解析运算符 ::
条件运算符 ?;
直接成员访问运算符 .
运算符 sizeof
四、运算符重载特点
1、提高了代码的易读性
2、也属于一种函数调用方式
3、它的本质是函数的重载
五、实现基本的运算符重载
#include<iostream>
using namespace std;
//初始化
class CComplex
{
public:
class CComplex()
:_real(int()),_image(int())
{}
CComplex(int real, int image)
:_real(real), _image(image)
{}
//拷贝构造函数
CComplex(const CComplex &src)
:_real(src._real), _image(src._image)
{}
//等号运算符的重载函数
CComplex &operator=(const CComplex& src)
{
if (this == &src)
{
return *this;
}
_real = src._real;
_image = src._image;
return *this;
}
//+运算符的重载 (this,CComplex&)
CComplex operator+(/*this,*/const CComplex& src)
{
return CComplex(_real + src._real, _image + src._image);
}
//+运算符的重载 (this,int)
CComplex operator+(int a)
{
return CComplex(_real + a, _image);
}
// -运算符的重载 (this,CComplex&)
CComplex operator-(const CComplex& src)
{
return CComplex(_real - src._real, _image - src._image);
}
// -运算符的重载 (this,int)
CComplex operator-(int a)
{
return CComplex(_real - a, _image);
}
//输出运算符的重载
ostream& operator<<(/*this,*/ostream &out)//cout<<c3
{
out << _real << " ";
out << _image << " ";
return out;
}
//输入运算符的重载
istream& operator>>(istream& in)
{
in >> _real;
in >> _image;
return in;
}
//前置++
const CComplex &operator++(/*this*/)
{
++_real;
++_image;
return *this;
}
//后置++
const CComplex operator++(int)
{ //10 15
return CComplex(_real++, _image++);//CComplex(10,15)
}
//前置--
const CComplex &operator--()
{
--_real;
--_image;
return *this;
}
//后置--
const CComplex operator--(int)
{
return CComplex(_real--,_image--);//这里返回的是一个临时量
}
//临时量是一个常量,不可以修改
bool operator==(const CComplex& src)
{
return (_real == src._real && _image == src._image);
}
void show()
{
cout << _real << " " << _image << endl;
}
private:
int _real;
int _image;
friend CComplex operator+(int a, const CComplex& src);
friend CComplex operator-(int a, const CComplex& src);
friend ostream& operator<<(ostream & out, const CComplex &src);
friend istream& operator>>(istream& in, CComplex &src);
};
//+ 运算符的重载 (int,CComplex)
CComplex operator+(int a, const CComplex& src)
{
return CComplex(src._real + a, src._image);
}
//- 运算符的重载 (int,CComplex)
CComplex operator-(int a, const CComplex& src)
{
return CComplex(a - src._real, src._image);
}
//输出运算符重载
ostream& operator<<(ostream & out, const CComplex &src)
{
out << src._real << " ";
out << src._image << " ";
return out;
}
//输入运算符重载
istream& operator>>(istream & in, CComplex &src)
{
in>>src._real;
in>>src._image;
return in;
}