友元函数是怎样用的?

2024-12-21 13:03:01
推荐回答(2个)
回答1:

#include
#include
class CDisplay;/*声明一个类*/

class CStudent{
private:
char m_name[20];
int m_id;
char m_gender;
int m_age;
public:
CStudent(char *,int,char,int);
friend class CDisplay;/*类CDdisplay是CStudent的友元类*/
};
CStudent::CStudent(char *name,int id,char gender,int age)
{
strcpy(m_name,name);
m_id=id;
m_gender=gender;
m_age=age;

}

class CDisplay{
friend void main();/*因为main函数要调用类CDdisplay的私有成员,故把它声明为类CDdisplay的友元函数。*/
void output(CStudent &stu);/*c++的类的定义若没声明成员所属"public,protected,或private",则默认为私有的。*/
};

void CDisplay::output(CStudent &stu)
{
cout<<"姓名"< cout<<"学号"< cout<<"性别"< cout<<"年龄"<}

void main()
{
CStudent stu("xiaohong",101,'f',20);
CDisplay dis;/*定义一个类,不应加括号*/
dis.output(stu);
}
/*其实定义友元函数的目的,就是为了使该函数能够访问其对应类的私有成员,如:上述的 friend void main();,而友元类与此相似,
就是为了能够访问其对应类的私有成员,如:上述的friend class CDisplay;这下你该明白了吧,要不明白,再问我,呵呵,程序已改好,
不过好像运行很慢,可能是我的电脑原因*/

回答2:

#include
#include
class CDisplay;

class CStudent{
private:
char m_name[20];
int m_id;
char m_gender;
int m_age;
public:
CStudent(char *,int,char,int);
friend void output(CStudent &stu);
};

CStudent::CStudent(char *name,int id,char gender,int age)
{
strcpy(m_name,name);
m_id=id;
m_gender=gender;
m_age=age;

}

void output(CStudent &stu)
{
cout<<"姓名"< cout<<"学号"< cout<<"性别"< cout<<"年龄"<}

void main()
{
CStudent stu("xiaohong",101,'f',20);
output( stu);

}