运算符的重载实质是函数的重载
形式有两种:类的成员函数和友元函数形式
类的成员函数的形式:
函数类型 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
}