運算符的重載實質是函數的重載
形式有兩種:類的成員函數和友元函數形式
類的成員函數的形式:
函數類型 operator運算符(參數);
友元函數格式:
friend 函數類型 operator運算符(參數);
注意事項:
(1)運算符重載不允許發明新的運算符
(2)不改變運算符的優先級
(3)不能改變運算符的操作對象個數
(4)5個不能重載的運算符(:: . ?: .* sizeof)
(5)一般情況下,單目運算符重載爲類的成員函數,雙目運算符重載爲友元函數
(6)不能重載爲友元函數的運算符有(= () [ ] -> )
(7)流運算符只能重載爲友元函數
(8)類型轉換運算符只能使用類的成員函數重載
下面看一個程序:
Complex.h文件:
#ifndef _COMPLEX_H_
#define _COMPLEX_H_
class Complex
{
private:
int real_;
int imag_;
public:
Complex(int real, int imag);
~Complex();
void Dispaly();
Complex& add(const Complex &other);
Complex& operator+(const Complex &other);
friend Complex operator+(const Complex &c1, const Complex &c2);
};
#endif
Complex.cpp文件:
#include <iostream>
#include "complex.h"
using namespace std;
Complex::Complex(int real, int imag):real_(real),imag_(imag)
{
}
Complex::~Complex()
{
}
void Complex::Dispaly()
{
cout<<real_<<"+"<<imag_<<"i"<<endl;
}
Complex& Complex::add(const Complex &other)
{
real_ += other.real_;
imag_ += other.imag_;
return *this;
}
Complex& Complex::operator+(const Complex &other)
{//類的成員函數實現運算符重載,在vs中可與下面的方法共存,成員優先級高
int real = real_ + other.real_;
int imag = imag_ + other.imag_;
return Complex(real,imag);
}
Complex operator+(const Complex &c1, const Complex &c2)
{//友元函數實現運算符重載,
int real = c1.real_ + c2.real_;
int imag = c1.imag_ + c2.imag_;
return Complex(real,imag);
}
主文件:
#include "complex.h"
int main()
{
Complex c1(3,5);
Complex c2(3,6);
c2.add(c1);
c2.Dispaly(); //6+11i
Complex c3(4,8);
c3 = c1+c2; //c1.operator+(c2) 或者 operate+(c1,c2)
c1.Dispaly(); //3+5i
c2.Dispaly(); //6+11i
c3.Dispaly(); //9+16i
}