"運算符"幾乎是所有的編程語言中都會出現(xiàn)的概念,例如+、-、*、/ 就是最常見的運算符。C++預(yù)定義的運算符只能作用于C++已經(jīng)定義的基本數(shù)據(jù)類型,對于用戶自定義的類型,如果也需要進行類似的運算操作的話,就需要重新去定義這些運算,賦予運算符新的功能,即"運算符重載"。
一、運算符重載時需要注意的點
- 運算符重載不改變運算符的"優(yōu)先級"與"結(jié)合性",也不改變運算符的操作數(shù)個數(shù)。
- 重載運算符時不應(yīng)該改變運算符的含義,比如說"+"重載之后仍然表示加法的含義。
- 運算符重載的本質(zhì)是函數(shù)重載,運算符函數(shù)可以作為成員函數(shù),也可以作為非成員函數(shù),作為非成員函數(shù)時一般為友元函數(shù)。
- 在大多數(shù)情況下,將運算符函數(shù)重載為類的成員函數(shù)和類的友元函數(shù)都是可以的。但是要注意下面幾個運算符函數(shù)必須要重載為成員函數(shù):=、[]、()、->。
- C++中大部分運算符都是可以被重載的,但是有5個運算符不允許被重載:"."、".*"、"::"、"?:"、"sizeof"。
二、運算符重載的語法:
<返回值類型> operator<運算符>(<形參列表>)
{
//函數(shù)體
}
三、運算符重載實例(復(fù)數(shù)類)
#include <IOStream>
using namespace std;
class Complex
{
public:
Complex(int real, int imag);
~Complex();
// 成員函數(shù)重載運算符
Complex& operator+(const Complex& c);
// 友元函數(shù)重載"流操作運算運算符"
friend ostream& operator<<(ostream& out, const Complex& c);
private:
int real_;
int imag_;
};
Complex::Complex(int real, int imag)
{
real_ = real;
imag_ = imag;
}
Complex::~Complex()
{
}
Complex& Complex::operator+(const Complex& c)
{
this->real_ += c.real_;
this->imag_ += c.imag_;
return *this;
}
ostream& operator<<(ostream& out, const Complex& c)
{
out << c.real_;
if(c.imag_ > 0)
out << "+" << c.imag_ << "i";
else
out << c.imag_ << "i";
return out;
}
int main()
{
Complex a(4, -6);
cout << a << endl; // 等于operator<<(cout, a);
Complex b(4, 3);
cout << b << endl;
Complex c = a + b;
cout << c << endl;
return 0;
}
