<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                合規國際互聯網加速 OSASE為企業客戶提供高速穩定SD-WAN國際加速解決方案。 廣告
                # C++ 中的友元類和友元函數 > 原文: [https://beginnersbook.com/2017/09/friend-class-and-friend-functions/](https://beginnersbook.com/2017/09/friend-class-and-friend-functions/) 我們知道一個類無法訪問其他類的私有成員。類似地,不繼承另一個類的類不能訪問其受保護的成員。 **友元類:** **友元類**是一個類,可以訪問被聲明為**友元**的類的私有成員和受保護成員。當我們想要允許特定類訪問類的私有成員和受保護成員時,這是必需的。 ## 函數類示例 在這個例子中,我們有兩個類`XYZ`和`ABC`。 `XYZ`類有兩個私有數據成員`ch`和`num`,這個類將`ABC`聲明為友元類。這意味著`ABC`可以訪問`XYZ`的私有成員,在`ABC`類的函數`disp()`訪問私有成員`num`和`ch`的示例中也證明了這一點。在這個例子中,我們[將對象作為參數傳遞給函數](https://beginnersbook.com/2017/09/cpp-pass-and-return-object-from-a-function/)。 ```cpp #include <iostream> using namespace std; class XYZ { private: char ch='A'; int num = 11; public: /* This statement would make class ABC * a friend class of XYZ, this means that * ABC can access the private and protected * members of XYZ class. */ friend class ABC; }; class ABC { public: void disp(XYZ obj){ cout<<obj.ch<<endl; cout<<obj.num<<endl; } }; int main() { ABC obj; XYZ obj2; obj.disp(obj2); return 0; } ``` **輸出:** ```cpp A 11 ``` **友元函數:** 與友元類相似,此函數可以訪問另一個類的私有和受保護成員。全局函數也可以聲明為友元,如下例所示: ## 友元函數示例 ```cpp #include <iostream> using namespace std; class XYZ { private: int num=100; char ch='Z'; public: friend void disp(XYZ obj); }; //Global Function void disp(XYZ obj){ cout<<obj.num<<endl; cout<<obj.ch<<endl; } int main() { XYZ obj; disp(obj); return 0; } ``` **輸出:** ```cpp 100 Z ```
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看