友元函数
在类的声明中可以声明某一个函数作为该类的友元函数,然后该函数就可以访问类中的private数据成员了。
demo:
/*
wirten by qianshou
2013/12/6
04:13 pm
study at SDNU
*/
#include<iostream>
using namespace std;
class Time
{
public:
Time(int h,int m,int s);
friend void display(Time &t);//声明display函数为本类的友元成员函数
void show();
private:
int hour;
int minute;
int second;
};
class Date
{
public:
Date(int,int,int);
friend void display(Date &d);//声明display函数为本类的友元成员函数
private:
int month;
int day;
int year;
};
Time::Time(int h,int m,int s)//Time的构造函数
{
hour=h;
minute=m;
second=s;
}
void Time::show()
{
cout<<hour<<":"<<minute<<":"<<second<<endl;
}
void display(Date &d) //用于输出Date数据的display函数
{
cout<<d.month<<"/"<<d.day<<"/"<<d.year<<endl;
}
void display(Time &t) //用于输出Time数据的display函数
{
t.show();
}
Date::Date(int m,int d,int y)//Date的构造函数
{
month=m;
day=d;
year=y;
}
int main()
{
Time t1(12,30,45);
Date d1(12,6,2013);
display(d1);
display(t1);
return 0;
}
display函数是类Date和Time的友元函数,通过重载函数dispaly(根据传递的参数不同),实现对Time类对象和Date类对象的输出。
程序输出结果:
/*****
12/6/2013
12:30:45
*******/
友元成员函数
在类A的定义中,声明类B的成员函数fun()作为类A的友元成员函数。那么类B的成员函数fun()就可以访问类A中的数据成员了。
demo:
/*
wirten by qianshou
2013/12/6
study at SDNU
*/
#include<iostream>
using namespace std;
class Date; //对类的提前声明
class Time
{
public:
Time(int h,int m,int s);
void display(Date &d);
private:
int hour;
int minute;
int second;
};
class Date
{
public:
Date(int,int,int);
friend void Time::display(Date &);//声明Time类中的display函数为本类的友元成员函数
private:
int month;
int day;
int year;
};
Time::Time(int h,int m,int s) //Time的构造函数
{
hour=h;
minute=m;
second=s;
}
void Time::display(Date &d) //对类Time中的成员函数display的定义
{
cout<<d.month<<"/"<<d.day<<"/"<<d.year<<endl;
cout<<hour<<":"<<minute<<":"<<second<<endl;
}
Date::Date(int m,int d,int y) //Date的构造函数
{
month=m;
day=d;
year=y;
}
int main()
{
Time t1(12,30,45);
Date d1(12,6,2013);
t1.display(d1);
return 0;
}
在类Date中,声明了Time类中的display函数作为Date类的友元函数,因此在display函数中既可以访问Time类中的数据成员,又可以访问Date类中的数据成员。
程序输出结果:
/*****
12/6/2013
12:30:45
*******/
友元类
声明类B为类A的友元类,然后类B中的成员函数就可以访问类A中的数据成员了。但是,要注意友元的关系是单向的,即A声明了B是它的友元之后,B中的成员函数可以访问A中的private数据成员,但是A不能访问B中的private数据成员。
demo:
/*
wirten by qianshou
2013/12/6
study at SDNU
*/
#include<iostream>
using namespace std;
class Date; //对类的提前声明
class Time
{
public:
Time(int h,int m,int s);
void display(Date &d);
private:
int hour;
int minute;
int second;
};
class Date
{
public:
Date(int,int,int);
friend Time;//声明Time类是它的友元类
private:
int month;
int day;
int year;
};
Time::Time(int h,int m,int s) //Time的构造函数
{
hour=h;
minute=m;
second=s;
}
void Time::display(Date &d) //对类Time中的成员函数display的定义
{
cout<<d.month<<"/"<<d.day<<"/"<<d.year<<endl;
cout<<hour<<":"<<minute<<":"<<second<<endl;
}
Date::Date(int m,int d,int y) //Date的构造函数
{
month=m;
day=d;
year=y;
}
int main()
{
Time t1(12,30,45);
Date d1(12,6,2013);
t1.display(d1);
return 0;
}
在Date类中声明了Time类作为它的友元类,所以Time类的成员函数display可以访问Date类中的私有成员。
程序输出结果:
/*****
12/6/2013
12:30:45
*******/