1. 程式人生 > 其它 >C++學習練習 之左移運算子過載

C++學習練習 之左移運算子過載

技術標籤:C/C++c++程式語言

C++學習練習
之左移運算子過載

當我們建立了一個類

class Person{
    public:
        int m_A;
        int m_B;
};

想訪問類中的成員的時候,卻不能 cout << p 返回成員值。

void test01(){
    Person p;
    p.m_A = 10;
    p.m_B = 10;

    cout << p.m_A << endl;
    cout << p.m_B << endl;
    // cout << p << endl;
}

此時可以用過載的方法過載 <<

ostream & operator<< (ostream &cout , Person &p){  //本質  operator<< (cout , p) 簡化cout << p;
    cout << "m_A = " << p.m_A << "   m_B = " << p.m_B;
    return cout;
}

但是隻能運用全域性函式過載左移運算子
我們平時建立一個類的時候,成員一般都寫成private

但此時,我們過載的方法就會報錯,原因是成員變數變成了私有變數。
這時,我們可以用友元來解決這個問題

class Person{

    //寫成友元即可
    friend ostream & operator<< (ostream &cout , Person &p);
    friend void test01();
    private:

    //利用成員函式過載左移運算子  p.operator<< (cout)  簡化版本 p << cout
    //不會利用成員函式過載<< 運算子,因為無法實現cout在左側
int m_A; int m_B; };

程式碼示例:

#include <iostream>
using namespace std;

class Person{

    //寫成友元即可
    friend ostream & operator<< (ostream &cout , Person &p);
    friend void test01();
    private:

    //利用成員函式過載左移運算子  p.operator<< (cout)  簡化版本 p << cout
    //不會利用成員函式過載<< 運算子,因為無法實現cout在左側
        int m_A;
        int m_B;
};

//只能運用全域性函式過載左移運算子
ostream & operator<< (ostream &cout , Person &p){  //本質  operator<< (cout , p) 簡化cout << p;
    cout << "m_A = " << p.m_A << "   m_B = " << p.m_B;
    return cout;
}

void test01(){
    Person p;
    p.m_A = 10;
    p.m_B = 10;

    cout << p.m_A << endl;
    cout << p.m_B << endl;
    cout << p << endl;
}

int main(){
    test01();
    system("pause");
    return 0;
}

在這裡插入圖片描述
學習資源:https://www.bilibili.com/video/BV1et411b73Z?p=122