C++左移運算符重載


  • 函數定義期望
  1. 通過cout<<對象,打印出復數的實部和虛部,這樣一來,就需要重載cout類的位移<<運算函數,但是我們並不能拿到cout源碼,在visual studio我們看到的也僅僅是他的定義
  2. 若想訪問c1的私有屬性,則應當聲明為友元函數
  3. 通過定義可以看出cout類的返回值是ostream類型的變量out
void operator<<(ostream &out, cplxaddself &c1)
{
    out << "陳培昌" << endl;
    out << c1.a << "+" << c1.b<<"i" << endl;
}
  • 類定義
#include <iostream>
#include<string.h>
using namespace std;
class cplxaddself
{
public:
    friend void operator<<(ostream &out, cplxaddself &c1);
    cplxaddself::cplxaddself(int a,int b)
    {
        this->a = a;
        this->b = b;
    }
    
    void printmyself()
    {
        cout <<"復數:"<< this->a << "+" << this->b << "i" << endl;
    }
    

private:
    int a;
    int b;
};
  • 主函數文件
void main()
{
    cplxaddself c1(4, 6),c3(0,0);
    cplxaddself c2 = c1;
    cout << c2;
    system("pause");
}

輸出結果:

 

皆大歡喜,.......不過,要是以為事情結束那就太簡單了

如果我們稍加修改就報錯了,其實真正實現的理想方案是滿足鏈式編程

void main()
{
    cplxaddself c1(4, 6),c3(0,0);
    cplxaddself c2 = c1;
    cout << c2<<endl;//報錯
    system("pause");
}

所以位移運算需要重載為

ostream& operator<<(ostream &out,cplxaddself &cplx)
{
    out << "queen of rain" << endl;
    out << cplx.a << "+" << cplx.b << "i" << endl;
    return out;
}
void main()
{
    cplxaddself c1(4, 6),c3(0,0);
    cplxaddself c2 = c1;
    c1++;
    cout <<"before:"<< c2<<" after: "<<c1;
    system("pause");
}

輸出結果:


免責聲明!

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



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