数学运算符的重载
四则运算符
(+、-、、/、+=、-=、=、/=)和关系运算符
(>、<、<=、>=、==、!=)都是数学运算符,它们在实际开发中非常常见,被重载的几率也很高,并且有着相似的重载格式。代码如下:
//各类运算符的重载!
#include <iostream>
#include <cmath>
using namespace std;
//复数类
class Complex{
public: //构造函数,使用有默认参数的构造函数
Complex(double real = 0.0, double imag = 0.0): m_real(real), m_imag(imag){ }
public: //运算符重载
//以全局函数的形式重载,加友元函数声明,参数是两个!
friend Complex operator+(const Complex &c1, const Complex &c2);
friend Complex operator-(const Complex &c1, const Complex &c2);
friend Complex operator*(const Complex &c1, const Complex &c2);
friend Complex operator/(const Complex &c1, const Complex &c2);
friend bool operator==(const Complex &c1, const Complex &c2);
friend bool operator!=(const Complex &c1, const Complex &c2);
//以成员函数的形式重载,参数是一个,隐式调用this指针
Complex & operator+=(const Complex &c);
Complex & operator-=(const Complex &c);
Complex & operator*=(const Complex &c);
Complex & operator/=(const Complex &c);
public: //成员函数
double real() const{ return m_real; }
double imag() const{ return m_imag; }
private:
double m_real; //实部
double m_imag; //虚部
};
//重载+运算符
Complex operator+(const Complex &c1, const Complex &c2){
Complex c;
c.m_real = c1.m_real + c2.m_real;
c.m_imag = c1.m_imag + c2.m_imag;
return c;
}
//重载-运算符
Complex operator-(const Complex &c1, const Complex &c2){
Complex c;
c.m_real = c1.m_real - c2.m_real;
c.m_imag = c1.m_imag - c2.m_imag;
return c;
}
//重载*运算符 (a+bi) * (c+di) = (ac-bd) + (bc+ad)i
Complex operator*(const Complex &c1, const Complex &c2){
Complex c;
c.m_real = c1.m_real * c2.m_real - c1.m_imag * c2.m_imag;
c.m_imag = c1.m_imag * c2.m_real + c1.m_real * c2.m_imag;
return c;
}
//重载/运算符 (a+bi) / (c+di) = [(ac+bd) / (c2+d2)] + [(bc-ad) / (c2+d2)]i
Complex operator/(const Complex &c1, const Complex &c2){
Complex c;
c.m_real = (c1.m_real*c2.m_real + c1.m_imag*c2.m_imag) / (pow(c2.m_real, 2) + pow(c2.m_imag, 2));
c.m_imag = (c1.m_imag*c2.m_real - c1.m_real*c2.m_imag) / (pow(c2.m_real, 2) + pow(c2.m_imag, 2));
return c;
}
//重载==运算符,布尔型
bool operator==(const Complex &c1, const Complex &c2){
if( c1.m_real == c2.m_real && c1.m_imag == c2.m_imag ){
return true;
}else{
return false;
}
}
//重载!=运算符
bool operator!=(const Complex &c1, const Complex &c2){
if( c1.m_real != c2.m_real || c1.m_imag != c2.m_imag ){
return true;
}else{
return false;
}
}
//重载+=运算符
Complex & Complex::operator+=(const Complex &c){
this->m_real += c.m_real;
this->m_imag += c.m_imag;
return *this;
}
//重载-=运算符
Complex & Complex::operator-=(const Complex &c){
this->m_real -= c.m_real;
this->m_imag -= c.m_imag;
return *this;
}
//重载*=运算符
Complex & Complex::operator*=(const Complex &c){
this->m_real = this->m_real * c.m_real - this->m_imag * c.m_imag;
this->m_imag = this->m_imag * c.m_real + this->m_real * c.m_imag;
return *this;
}
//重载/=运算符
Complex & Complex::operator/=(const Complex &c){
this->m_real = (this->m_real*c.m_real + this->m_imag*c.m_imag) / (pow(c.m_real, 2) + pow(c.m_imag, 2));
this->m_imag = (this->m_imag*c.m_real - this->m_real*c.m_imag) / (pow(c.m_real, 2) + pow(c.m_imag, 2));
return *this;
}
int main(){
Complex c1(25, 35);
Complex c2(10, 20);
Complex c3(1, 2);
Complex c4(4, 9);
Complex c5(34, 6);
Complex c6(80, 90);
Complex c7 = c1 + c2;
Complex c8 = c1 - c2;
Complex c9 = c1 * c2;
Complex c10 = c1 / c2;
cout<<"c7 = "<<c7.real()<<" + "<<c7.imag()<<"i"<<endl;
cout<<"c8 = "<<c8.real()<<" + "<<c8.imag()<<"i"<<endl;
cout<<"c9 = "<<c9.real()<<" + "<<c9.imag()<<"i"<<endl;
cout<<"c10 = "<<c10.real()<<" + "<<c10.imag()<<"i"<<endl;
c3 += c1;
c4 -= c2;
c5 *= c2;
c6 /= c2;
cout<<"c3 = "<<c3.real()<<" + "<<c3.imag()<<"i"<<endl;
cout<<"c4 = "<<c4.real()<<" + "<<c4.imag()<<"i"<<endl;
cout<<"c5 = "<<c5.real()<<" + "<<c5.imag()<<"i"<<endl;
cout<<"c6 = "<<c6.real()<<" + "<<c6.imag()<<"i"<<endl;
if(c1 == c2){
cout<<"c1 == c2"<<endl;
}
if(c1 != c2){
cout<<"c1 != c2"<<endl;
}
return 0;
}
需要注意的是,我们这里以全局函数的形式重载了 +、-、*、/、==、!=
,以成员函数的形式重载了 +=、-=、*=、/=
,而且应该坚持这样做,不要一股脑都写作成员函数或者全局函数。点击查看原因
重载“<<”和“>>”
我们知道cout 是 ostream 类的对象,cin 是 istream 类的对象,iostream类则是继承他们的类
,要想达到这个目标,就必须以全局函数(友元函数)的形式重载<<和>>
,否则就要修改标准库中的类,这显然不是我们所期望的。代码如下:
#include <iostream>
using namespace std;
class complex{
public:
complex(double real = 0.0, double imag = 0.0): m_real(real), m_imag(imag){ };
public:
friend istream & operator>>(istream & in, complex & A);//注意传入的参数。
friend ostream & operator<<(ostream & out, complex & A);
private:
double m_real; //实部
double m_imag; //虚部
};
//重载输入运算符,返回istream类
istream & operator>>(istream & in, complex & A){
in >> A.m_real >> A.m_imag;
return in;
}
//重载输出运算符,返回的是ostream类
ostream & operator<<(ostream & out, complex & A){
out << A.m_real <<" + "<< A.m_imag <<" i ";;
return out;
}
int main(){
complex c1, c2;
cin>>c1>>c2;
cout<<"c1= "<<c1<<endl;
cout<<"c2 = "<<c2<<endl;
return 0;
}
重载“[]”
C++ 规定,下标运算符[ ]必须以成员函数的形式进行重载
。该重载函数在类中的声明格式如下:
返回值类型 & operator[ ] (参数);
或者:
const 返回值类型 & operator[ ] (参数) const;//常函数,只能访问,不能修改
使用第一种声明方式,[ ]
不仅可以访问元素,还可以修改元素。使用第二种声明方式,[ ]
只能访问而不能修改元素。在实际开发中,我们应该同时提供以上两种形式,这样做是为了适应 const 对象,因为通过 const 对象只能调用 const 成员函数,如果不提供第二种形式,那么将无法访问 const 对象的任何元素。
我们知道,有些较老的编译器不支持变长数组,例如 VC6.0、VS2010 等,这有时候会给编程带来不便,下面我们通过自定义的 Array 类来实现变长数组。
#include <iostream>
using namespace std;
class Array{
public:
//构造函数与析构函数
Array(int length = 0);
~Array();
public:
//成员函数重载[],返回值为int,参数只有一个。
int & operator[](int i);
const int & operator[](int i) const;
public:
//计算长度
int length() const { return m_length; }
//输出数组
void display() const;
private:
int m_length; //数组长度
int *m_p; //指向数组内存的指针
};
Array::Array(int length): m_length(length){
if(length == 0){
m_p = NULL;
}else{
m_p = new int[length];//分配空间
}
}
Array::~Array(){
delete[] m_p;
}
//成员函数重载[]
int& Array::operator[](int i){
return m_p[i];
}
const int & Array::operator[](int i) const{
return m_p[i];//返回数组元素m_p[i]
}
//输出数组
void Array::display() const{
for(int i = 0; i < m_length; i++){
if(i == m_length - 1){
cout<<m_p[i]<<endl;
}else{
cout<<m_p[i]<<", ";
}
}
}
int main(){
int n;
cin>>n;
Array A(n);//创建长度为n的数组
for(int i = 0, len = A.length(); i < len; i++){
A[i] = i * 5;//等比数组
}
A.display();
const Array B(n);//常对象只能调用常成员函数。我们无法修改对应数组的值。
cout<<B[n-1]<<endl; //访问最后一个元素,全是0
return 0;
}
重载[ ]运算符以后,表达式arr[i]会被转换为:
arr.operator[ ](i);//函数operator[],参数i
需要说明的是,B 是 const 对象,如果 Array 类没有提供 const 版本的operator[ ],那么第 60 行代码将报错。虽然第 60 行代码只是读取对象的数据,并没有试图修改对象,但是它调用了非 const 版本的operator[ ],编译器不管实际上有没有修改对象,只要是调用了非 const 的成员函数,编译器就认为会修改对象(至少有这种风险)。
重载“++、- -”
自增++和自减--都是一元运算符,它的前置形式和后置形式都可以被重载
#include <iostream>
#include <iomanip>
using namespace std;
//秒表类
class stopwatch{
public://缺省构造函数
stopwatch(): m_min(0), m_sec(0){ }
public:
void setzero(){ m_min = 0; m_sec = 0; }
stopwatch run(); // 运行,计时
//重载成员函数
stopwatch operator++(); //++i,前置形式
stopwatch operator++(int); //i++,后置形式
//友元函数实现输出
friend ostream & operator<<( ostream &, const stopwatch &);
private:
int m_min; //分钟
int m_sec; //秒钟
};
stopwatch stopwatch::run(){
++m_sec;
if(m_sec == 60){
m_min++;
m_sec = 0;
}
return *this;
}
//++前置
stopwatch stopwatch::operator++(){
return run();
}
//++后置 ,注意,int 在 括号内是为了向编译器说明这是一个后缀形式,而不是表示整数。
//前缀形式重载调用 operator ++ () ,后缀形式重载调用 operator ++ (int)。
stopwatch stopwatch::operator++(int){
stopwatch s = *this;
run();//m_sec增加
return s;
}
//重载<<
ostream &operator<<( ostream & out, const stopwatch & s){
out<<setfill('0')<<setw(2)<<s.m_min<<":"<<setw(2)<<s.m_sec;
return out;
}
int main(){
stopwatch s1, s2;
s1 = s2++;//后缀形式,s2赋值给s1,s2加1,
cout << "s1: "<< s1 <<endl;//00:00
cout << "s2: "<< s2 <<endl;//00:01
s1.setzero();//置零
s2.setzero();
s1 = ++s2;//前缀形式,s2+1,赋值给s1
cout << "s1: "<< s1 <<endl;//00:01
cout << "s2: "<< s2 <<endl;//00:01
return 0;
}
再次说明:加int表示后缀形式调用这个函数,而不是参数!
stopwatch stopwatch::operator++(int ){
stopwatch s = *this;
run();//m_sec增加
return s;
}
重载new和delete
内存管理运算符 new、new[]、delete 和 delete[]
也可以进行重载,其重载形式既可以是类的成员函数,也可以是全局函数
。一般情况下,内建的内存管理运算符就够用了,只有在需要自己管理内存时才会重载。
以成员函数的形式重载 new 运算符:
void * className::operator new( size_t size ){
//TODO:
}
以全局函数的形式重载 new 运算符:
void * operator new( size_t size ){
//TODO:
}
两种重载形式的返回值相同,都是void *类型,并且都有一个参数,为size_t类型
。在重载 new 或 new[] 时,无论是作为成员函数还是作为全局函数,它的第一个参数必须是 size_t 类型。size_t 表示的是要分配空间的大小,对于 new[] 的重载函数而言,size_t 则表示所需要分配的所有空间的总和。
size_t 在头文件 <cstdio> 中被定义为typedef unsigned int size_t;
,也就是无符号整型。
当然,重载函数也可以有其他参数,但都必须有默认值,并且第一个参数的类型必须是 size_t。
同样的,delete 运算符也有两种重载形式。以类的成员函数的形式进行重载:
void className::operator delete( void *ptr){
//TODO:
}
以全局函数的形式进行重载:
void operator delete( void *ptr){
//TODO:
}
两种重载形式的返回值都是 void 类型,并且都必须有一个 void 类型的指针作为参数,该指针指向需要释放的内存空间。
重载()
在 C++ 中,类型的名字(包括类的名字)本身也是一种运算符,即类型强制转换运算符
。
类型强制转换运算符是单目运算符,也可以被重载,但只能重载为成员函数,不能重载为全局函数
。经过适当重载后,(类型名)对象这个对对象进行强制类型转换的表达式就等价于对象.operator 类型名(),
即变成对运算符函数的调用。
下面的程序对 double 类型强制转换运算符进行了重载,实现复数转换为浮点数。
#include <iostream>
using namespace std;
class Complex
{
double real, imag;//默认private
public:
Complex(double r = 0, double i = 0) :real(r), imag(i) {};
operator double() { return real; } //重载强制类型转换运算符 double,实现复数转换为浮点数
};
int main()
{
Complex c(1.2, 3.4);
//(类型名)对象这个对对象进行强制类型转换的表达式就等价于对象.operator 类型名()
//相当于c.operator double()
cout << (double)c << endl; //输出 1.2
double n = 2 + c; //等价于 double n = 2 + c. operator double()
cout << n; //输出 3.2
}
程序的输出结果是:
1.2
3.2
第 8 行对 double 运算符进行了重载。重载强制类型转换运算符时,不需要指定返回值类型,因为返回值类型是确定的,就是运算符本身代表的类型
,在这里就是 double。
重载后的效果是,第 13 行的(double)c等价于c.operator double()。
注意:有了对 double 运算符的重载,在本该出现 double 类型的变量或常量的地方,如果出现了一个 Complex 类型的对象,那么该对象的 operator double 成员函数就会被调用,然后取其返回值使用。
例如第 14 行,编译器认为本行中c这个位置如果出现的是 double 类型的数据,就能够解释得通,而 Complex 类正好重载了 double 运算符,因而本行就等价于:
double n = 2 + c.operator double();
小结注意事项
在 C++ 中进行运算符重载时,有以下问题需要注意:
- 重载后运算符的含义应该符合原有用法习惯。例如重载+运算符,完成的功能就应该类似于做加法,在重载的+运算符中做减法是不合适的。此外,重载应尽量保留运算符原有的特性。
- C++ 规定,运算符重载不改变运算符的优先级。
- 下面是不可重载的运算符列表:
.
:成员访问运算符.*
,->*
:成员指针访问运算符::
:域运算符sizeof
:长度运算符?:
:条件运算符#
: 预处理符号
-
载运算符
()
、[]
、->
、或者赋值运算符=
时,只能将它们重载为成员函数,不能重载为全局函数。 -
运算符重载的实质是将运算符重载为一个函数,使用运算符的表达式就被解释为对重载函数的调用。
-
运算符可以重载为全局函数。此时函数的参数个数就是运算符的操作数个数,运算符的操作数就成为函数的实参。运算符也可以重载为成员函数。此时函数的参数个数就是运算符的操作数个数减一,运算符的操作数有一个成为函数作用的对象,其余的成为函数的实参。
-
必要时需要重载赋值运算符=,以避免两个对象内部的指针指向同一片存储空间。
-
运算符可以重载为全局函数,然后声明为类的友元。
-
<<
和>>
是在 iostream 中被重载,才成为所谓的“流插入运算符”和“流提取运算符”的。 -
类型的名字可以作为强制类型转换运算符,也可以被重载为类的成员函数。它能使得对象被自动转换为某种类型。如
double
-
自增、自减运算符各有两种重载方式,用于区别前置用法和后置用法。注意后缀形式
-
运算符重载不改变运算符的优先级。重载运算符时,应该尽量保留运算符原本的特性。