Friend function就是在class的public中加入local function的定義(實例仍寫在class外面),

以此擴充class的function。

好處:

  1. 可以用local function控制物件
  2. 似乎可以存取private data member

#include <iostream>
#include <limits.h>
using namespace std;


class Test
{

    friend int BigOne(Test&);

public:
    void Set3Value(int a,int b,int c)
    {
        T[0]=a;
        T[1]=b;
        T[2]=c;
    }

private:
    int T[3];
};

int BigOne(Test &t) /**用call by referance來傳遞物件,若用call by value太浪費時間空間且還會多產生一個物件**/
{
    int MaxValue = INT_MIN;
    for(int i=0;i<3;i++)
    {
        if(t.T[i]>MaxValue)
            MaxValue = t.T[i];
    }
    return MaxValue;
}

int main()
{
    int a,b,c;
    cin>>a>>b>>c;
    Test obj01;

    obj01.Set3Value(a,b,c);
    cout<<"Max is "<<BigOne(obj01)<<endl;
    return 0;
}
 

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 Kuihao 的頭像
    Kuihao

    溫暖午後的金針田__孕育有趣的創新

    Kuihao 發表在 痞客邦 留言(0) 人氣()