過載 +,-,*,/ 運算子
阿新 • • 發佈:2018-11-23
一、格式
返回值型別 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; }