一方面,在C++中,运算符重载( operator overloading)允许把标准运算符(如+ - * / % 等)应用于自定义数据类型的对象。
这样可以直观自然地看出自定义数据类型间的运算,并且提高程序的可读性。
另一方面,运算符重载仅仅是一种语法上的方便。默认运算符的本质就是函数的调用,而运算符重载就是另一种调用。
同时,虽然很多时候使用运算符重载可以提高程序的可读性,但我们不应该过于依赖,甚至是滥用它。只有在所涉及的代码更容易表达,尤其是更容易被读懂时才有必要重载。
例:
<pre name="code" class="cpp">#include <iostream>
using namespace std ;
class Complex{
int real_ ;
int imag_ ;
public :
Complex(int real , int imag) : real_(real) , imag_(imag) { }
Complex() : real_(0) , imag_(0) { }
Complex Add(const Complex& other){
real_ += other.real_ ;
imag_ += other.imag_ ;
return *this ;
}
~Complex() {};
void Display() const {
cout << real_ << " + " << imag_ << "i" << endl ;
}
};
int main(void) {
Complex c1(3 , 5) ;
Complex c2(4 , 6) ;
c1.Add(c2) ;
c1.Display() ;
return 0 ;
}
我们在不使用运算符重载的情况下,实现了两个复数相加的操作。
但是缺点非常明显,这样的方式非常不直观,如果我们希望 Complex c3 = c1 + c2 ;
这样直观的表现的话,编译器就会告诉我们,类的对象不能直接参与运算。
但如果我们有了运算符重载这个利器的话,上面的问题就会迎刃而解。
1. 成员函数重载
成员函数声明的格式 :
返回值类型 operator运算符 (参数列表) ;
成员函数定义的格式 :
返回值类型 类名::operator运算符 (参数列表) : {
// 需要实现的功能
}
例:以成员函数实现上面代码的功能
Complex operator+ (const Complex& other) ;
运算符“+”是一个二元运算符,运算时需要其左边和右边的对象,而成员函数必须由类的一个实例来调用,如使用c1调用operator+时,编译器已经知道c1的存在,只需要输入另一个对象即可。真实的情况就是成员函数重载运算符时,首先会默认地调用隐式指针this,之后才调用参数列表中显式的对象作为参数,因此在成员函数重载时,只需要一个参数。
下面我们来实现这个新的功能
#include <iostream>
using namespace std ;
class Complex{
int real_ ;
int imag_ ;
public :
Complex(int real , int imag) : real_(real) , imag_(imag) { }
Complex() : real_(0) , imag_(0) { }
Complex operator+(const Complex& other){
int r = real_ + other.real_ ;
int i = imag_ + other.imag_ ;
return Complex(r, i) ;
}
~Complex() {};
void Display() const {
cout << real_ << " + " << imag_ << "i" << endl ;
}
};
int main(void) {
Complex c1(3 , 5) ;
Complex c2(4 , 6) ;
Complex c3 = c1 + c2 ;
c3.Display() ;
return 0 ;
}
2. 友元函数重载
C++中的函数一共有两种形式,成员函数和顶层函数,我们现在来讨论顶层函数如何去实现。
首先,普通的顶层函数有一个致命的缺陷,就是无法访问类的私有成员。因此我们只有通过友元函数来实现运算符重载。
友元函数声明原型:
friend 函数原型 operator运算符(参数列表) ;
友元函数定义原型:
friend 函数类型 类名::operator运算符(参数列表) ;
#include <iostream>
using namespace std ;
class Complex {
int real_ ;
int imag_ ;
public :
Complex(int real , int imag) : real_(real) , imag_(imag) { }
Complex() : real_(0) , imag_(0) { }
friend Complex operator+(const Complex& left , const Complex& right) ;
void Display() {
cout << real_ << " + " << imag_ << "i" << endl ;
}
~Complex() {} ;
};
Complex operator+(const Complex& left , const Complex& right) {
int r = left.real_ + right.real_ ;
int i = left.imag_ + right.imag_ ;
return Complex(r , i) ;
}
int main(void) {
Complex c1(3 , 5) , c2(4 , 6) ;
Complex c3 = c1 + c2 ;
c3.Display() ;
return 0 ;
}
这就是用友元函数实现的运算符重载。
3. 运算符重载的规则
①. 运算符重载不允许发明新的运算符;
②. 不能改变原有运算符操作对象的个数,即单目不得变双目等;
③. 运算符被重载后,其优先级和结合性不得发生改变
④. 不得被重载的运算符: 作用于运算符 ::
条件运算符 ? :
直接成员运算符 .
类成员一直引用 ->
sizeof运算符 sizeof