友元函数

有些情况下,允许特定的非成员函数访问一个类的私有成员,同时仍阻止一般的访问,这是很方便做到的。例如被重载的操作符,如输入或输出操作符,经常需要访问类的私有数据成员。
友元(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;
}

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