友元函數

有些情況下,允許特定的非成員函數訪問一個類的私有成員,同時仍阻止一般的訪問,這是很方便做到的。例如被重載的操作符,如輸入或輸出操作符,經常需要訪問類的私有數據成員。
友元(frend)機制允許一個類將對其非公有成員的訪問權授予指定的函數或者類,友元的聲明以friend開始,它只能出現在類定義的內部,友元聲明可以出現在類中的任何地方:友元不是授予友元關係的那個類的成員,所以它們不受其聲明出現部分的訪問控制影響。通常,將友元聲明成組地放在類定義的開始或結尾是個好主意。

友元函數

友元函數是指某些雖然不是類成員函數卻能夠訪問類的所有成員的函數。類授予它的友元特別的訪問權,這樣該友元函數就能訪問到類中的所有成員。

#include <iostream>
using namespace std;

class A
{
public:
    friend void set_show(int x, A &a);      //該函數是友元函數的聲明
private:
    int data;
};

void set_show(int x, A &a)  //友元函數定義,爲了訪問類A中的成員
{
    a.data = x;
    cout << a.data << endl;
}
int main(void)
{
    class A a;

    set_show(1, a);

    return 0;
}

以上轉自luoxn28的博客

mytime.h和mytime.cpp

#ifndef MYTIME01_H
#define MYTIME01_H
#include <iostream>
using namespace std;
class Time
{
public:
    Time();
    Time(int h,int m = 0);
    ~Time();
    void AddMin(int m);
    void AddHr(int h);
    void reset(int h = 0,int m = 0);
    void show()const;
    
    Time operator + (const Time & t)const;   //成員函數重載+,聲明部分
    Time operator - (const Time & t)const;     //成員函數重載-,聲明部分
	Time operator ++(int);
    
	friend Time operator --(Time & t,int);
	friend Time operator *(const Time & n,int m);
	friend void operator << (ostream & t_cout,const Time & t);
	
private:
    int hours;
    int minutes;
};
#endif // MYTIME01_H

#include "mytime01.h"

Time::Time()
{
    minutes = 0;
    hours = 0;
}

Time::Time(int h,int m)
{
	minutes = m;
	hours = h;
}

Time::~Time()   //析構函數
{
}
void Time :: AddMin(int m)
{
	minutes =+ m;
	minutes %= 60;
	hours += minutes/60;
}
void Time :: AddHr(int h)
{
	hours += h;
}
void Time :: reset(int h,int m)
{
	minutes = m;
	hours = h;
}
Time Time :: operator + (const Time & t)const  //重載+
{
	Time sum;
	sum.minutes=this->minutes+t.minutes;
	sum.minutes %= 60;
	sum.hours=this->hours+t.hours+sum.minutes/60;
	return sum;
}

Time Time :: operator - (const Time & t)const //重載-
{
	Time diff;
	int to1,to2;
	to1 = hours*60+minutes;
	to2 = t.hours*60+t.minutes;
	diff.minutes = (to1-to2)%60;
	diff.hours = (to1-to2)/60;
	return diff;
}

Time Time :: operator ++ (int) //重載++
{
	Time sum =*this;
	this->minutes++;
	this->hours++;
	return sum;
}

Time operator --( Time & t,int) //友元重載--
{ 	
	Time diff = t; 	
	t.minutes--; 	
	t.hours--; 	
	return diff;	 
}
Time operator *(const Time & n,int m)友元重載*
{
	Time mul = n;
	int ta1 = n.minutes;
	int ta2 = n.hours*60;
	int tol = m*(ta1+ta2);
	mul.hours = tol/60;
	mul.minutes = tol%60;
	return mul;
}

void Time :: show()const
{
	std::cout <<hours << ":" << minutes << std::endl;
}
void operator << (std::ostream & t_cout,const Time & t) //重載<<   友元在類外實現不適用friend
{
	t_cout << t.hours << ":" << t.minutes << endl;
}

int main()
{
	Time t1(10,10);
	Time t2(20,20);
	Time t3 = t2-t1;
	t2 = t2*7;
	t2.show();
	return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章