重載 +,-,*,/ 運算符


一、格式

返回值類型 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;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM