程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> C++運算符重載——重載二元運算符

C++運算符重載——重載二元運算符

編輯:C++入門知識

(表示一個二元運算符),a ? b 的操作會被解釋為下面2種形式之一 

? b
a.(b);    
(a, b);  

 

 

 

2、應用舉例(對象 ? 對象)

#include <iostream>
 (Default constructor)
    ComplexA(){cout<<<<(The constructor with parameters)
    ComplexA( re,  im):real(re),image(im){cout<<<<(Copy constructor)
    ComplexA( ComplexA& ){real = .real; image = .image; cout<<<<(destructor)
    ~ComplexA(){cout<<<<
    ComplexA +(ComplexA&  ComplexA(real + .real, image + 
    ComplexA -(ComplexA&  ComplexA(real - .real, image - 
    ComplexA *(ComplexA&  ComplexA(real * .real, image * 
    ComplexA /(ComplexA&  ComplexA(real / .real, image / 
     display(){cout<<real<<<<image<<<< real;    
     image;   
(Default constructor)
    ComplexB(){cout<<<<(The constructor with parameters)
    ComplexB( re,  im):real(re),image(im){cout<<<<(Copy constructor)
    ComplexB( ComplexB& ){real = .real; image = .image; cout<<<<(destructor)
    ~ComplexB(){cout<<<<
    friend ComplexB +(ComplexB& ref1, ComplexB& ComplexB(ref1.real + ref2.real, ref1.image +
    friend ComplexB -(ComplexB& ref1, ComplexB& ComplexB(ref1.real - ref2.real, ref1.image -
    friend ComplexB *(ComplexB& ref1, ComplexB& ComplexB(ref1.real * ref2.real, ref1.image *
    friend ComplexB /(ComplexB& ref1, ComplexB& ComplexB(ref1.real / ref2.real, ref1.image /
     display(){cout<<real<<<<image<<<< real;    
     image;   
(Default constructor)
    ComplexC(){cout<<<<(The constructor with parameters)
    ComplexC( re,  im):real(re),image(im){cout<<<<(Copy constructor)
    ComplexC( ComplexC& ){real = .real; image = .image; cout<<<<(destructor)
    ~ComplexC(){cout<<<<
     GetReal(){ GetImage(){
display(){cout<<real<<<<image<<<< real; image; ComplexC +(ComplexC& ref1, ComplexC& ComplexC(ref1.GetReal() + ref2.GetReal(), ref1.GetImage() + ComplexC -(ComplexC& ref1, ComplexC& ComplexC(ref1.GetReal() - ref2.GetReal(), ref1.GetImage() - ComplexC *(ComplexC& ref1, ComplexC& ComplexC(ref1.GetReal() * ref2.GetReal(), ref1.GetImage() * ComplexC /(ComplexC& ref1, ComplexC& ComplexC(ref1.GetReal() / ref2.GetReal(), ref1.GetImage() / main(,), C2(, = C1 += C1 -= C1 *= C1 /<<<<,), C5(, = C4 += C4 -= C4 *= C4 /<<<<,), C8(, = C7 += C7 -= C7 *= C7 /

,或者反過來 ,這時上面的程序的重載方式就不適用了。

 

#include <iostream>
  re = ,  im = +(ComplexD& ){ ComplexD(real+.real, image++( a){cout<<; ComplexD(real++( d){cout<<; ComplexD(real++( f){cout<<; ComplexD(real+ display(){cout<<real<<<<image<<<< GetReal(){ GetImage(){+( a, ComplexD& ){cout<<; ComplexD(.GetReal()+a, +( d, ComplexD& ){cout<<; ComplexD(.GetReal()+d, +( f, ComplexD& ){cout<<; ComplexD(.GetReal()+f,  main(,= D1 + = D1 + = D1 + =  +=  +=  + 

 

 

 

 

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved