一、格式
返回值類型 operator 運算符(形參表) { . . . . . . }
二、試例
#include<iostream> using namespace std; class Complex { public : int real; int imag; Complex(int a=0,int b=0):real(a),imag(b) {}//構造函數 Complex operator-(const Complex &c)//運算符重載 { return Complex(real-c.real,imag-c.imag);//調用類中的構造函數 } }; Complex operator+(const Complex &a,const Complex &b)//運算符重載 { return Complex(a.real+b.real,a.imag+b.imag);//原理:調用類中的構造函數 } int main() { Complex a(4,4),b(1,1),c; c=a+b; cout<<"c="<<c.real<<" "<<c.imag<<endl; cout<<"a="<<a.real<<" "<<a.imag<<endl; a=a-b; cout<<"a="<<a.real<<" "<<a.imag<<endl; return 0; }
