【一天一篇CPP】友元和类

1.一般友元函数【就像可访问私有成员的一般函数】:

一个例子:

#include <iostream>

using namespace std;

class Time{
public:
	Time( int, int, int);
	friend void display(Time &);//先声明,使一般函数display可以访问本类的私有成员

private:
	int hour, minute, sec;
};

Time::Time(int h, int m, int s)
{
	hour = h;
	minute = m;
	sec = s;
}

void display(Time &t)
{
	cout << t.hour <<':'<< t.minute << ':' << t.sec <<endl;
}

int main()
{
	Time t1(10,13,56);
	display(t1);
	return 0;
}

2.友元成员函数:一个例子【对其他类的成员函数不设防】

#include <iostream>

using namespace std;

class Date;

class Time{
public:
	Time( int, int, int);
	void display(Date &);

private:
	int hour, minute, sec;
};

class Date{

public:
	Date( int, int, int);
	friend void Time::display(Date &);	//先声明,对它不设防。要记得制定是那个类的【Time::】
private:
	int year, month, day;
};

Time::Time(int h, int m, int s)
{
	hour = h;
	minute = m;
	sec = s;
}

Date::Date(int y, int m, int d)
{
	year = y;
	month = m;
	day = d;
}


void Time::display(Date &d)
{
	cout << d.year <<'.'<< d.month << '.' << d.day <<endl;
	cout << hour <<':'<< minute << ':' << sec <<endl;
}

int main()
{
	Time t1(10,13,56);
	Date d1(2013,9,26);

	t1.display(d1);
}
【提示:在这里用到了类的提前声明,解决两个类相互包含的问题。

累得提前声明只能用在互相包含的声明中,而不能用在定义之前,例如class Date; Date d1;是错误的,因为提前声明不能让编译器知道类的大小。】


3.友元类:如

class A{............

friend  B;

........};//则B拥有访问A的私有成员的权限!

一个例子:

class Date{

public:
	
	Date( int, int, int);
	//friend void Time::display(Date &);	//先声明,对它不设防。要记得制定是那个类的【Time::】
	friend Time;
private:
	int year, month, day;
};
只是把上面的friend void Time::display(Date &),换成为friend Time即可。所以Time 可以访问 Date的数据。


4.关于友元:

A友元的关系是单向的,而非双向的,如上例子,A不能访问B的私有成员。

B友元的关系不能传递:若B是A的友元类,C是B的友元类,那么C不是A的友元类【除非额外声明】

C为了安全性,不使用友元类,多使用友元函数。




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值