c++中友元函数
来源:互联网 发布:有淘宝账号秒批七万 编辑:程序博客网 时间:2024/06/01 08:47
如果在本类以外的其他地方定义了一个函数(这个函数可以是不属于任何类的普通函数,也可以是其他类的成员函数),在类体中用friend对其进行声明,那么这个函数就称为本类的友元函数。友元函数可以访问这个类中的任何成员。
如何将一个函数声明为友元函数呢,我们就先来看一个程序吧
#include<iostream>
using namespace std;
class Clock
{
public :
Clock(int h,int m,int s)
{
hour=h;
minute=m;
second=s;
}
friend void display(Clock &);
private:
int hour;
int minute;
int second;
};
void display(Clock & t)
{
cout<<t.hour<<":"<<t.minute<<":"<<t.second<<endl;
}
int main()
{
Clock clock(10,20,30);
display(clock);
return 0;
}
你们注意到程序中友元函数的声明与定义形式了么。这里需要说明一下的是,友元函数使用类中的成员时必须在成员的前面加上类名。
这是普通函数作为友元函数,较为简单,下面来看看类的成员函数作为另一个类的友元函数
#include<iostream>
using namespace std;
class Date; //对Date类的提前引用的声明
class Clock
{
public:
Clock(int ,int,int);
void display(Date &);
private:
int hour;
int minute;
int second;
};
class Date
{
public:
Date(int ,int ,int);
friend void Clock::display(Date &);
private:
int year;
int month;
int day;
};
Clock::Clock(int h,int m,int s) //类外定义Clock的构造函数
{
hour=h;
minute=m;
second=s;
}
Date::Date(int y,int m,int d) //类外定义Date的构造函数
{
year=y;
month=m;
day=d;
}
void Clock::display(Date & d) //类外定义Clock的成员函数
{
cout<<d.year<<"/"<<d.month<<"/"<<d.day<<endl;
cout<<hour<<":"<<minute<<":"<<second<<endl;
}
int main()
{
Clock clock(11,02,10);
Date date(2014,11,29);
clock.display(date);
}
- [C/C++]C函数
- c 函数
- C函数
- C 函数
- C函数
- 【C++】函数
- C 函数
- C++:函数
- C函数
- [C++]函数
- C函数
- c 函数
- C函数
- [C++]函数
- C函数
- 【c++】函数
- 【C++】函数
- C 函数
- iOS常用动画
- Jsp内置对象范围大小和几个常用方法介绍
- 错排公式
- C++学习笔记(第14章->代码重用->包含,继承,多重继承,虚基类)
- 第1题:把二元查找树转变成排序的双向链表
- c++中友元函数
- Creativity
- STL Vector使用
- 恶补java(十二)-------final的用法
- 美国年终网购将至 UPS和联邦快递Fedex提前备战
- Mysql JDBC Hello World JAVA
- 将博客搬至CSDN
- PullToRefreshListView的item设置长按事件
- Hibernat 使用Criteria查询多对多关系(SET集合)条件