c++友元函数、友元类、友成员函数

时间:2023-03-10 01:09:53
c++友元函数、友元类、友成员函数

友元函数:不是类成员函数,是一个类外的函数,但是可以访问类所有成员。

class Point{
public:
friend void fun(Point t);//友元函数
private:
int a;
protected:
int b;
}; void fun(Point t)
{
t.a = ;
t.b = ;
cout << t.a << " " << t.b << endl;
} int main()
{
Point test;
fun(test);
system("pause");
return ;
}

运行结果:

c++友元函数、友元类、友成员函数

友元类:类A是类B的友元类,则A就可以访问B的所有成员(成员函数,数据成员)。(类A,类B无继承关系)

class Point{
friend class Line;
public:
void fun()
{
this->x = ;
this->y = ;
}
private:
int x;
protected:
int y;
}; class Line{
public:
void printXY()
{
t.fun();
cout << t.x << " " << t.y << endl;
} private:
Point t;
}; int main()
{
Line test;
test.printXY();
system("pause");
return ;
}

运行结果:

c++友元函数、友元类、友成员函数

友成员函数:使类B中的成员函数成为类A的友元函数,这样类B的该成员函数就可以访问类A的所有成员(成员函数、数据成员)了

 class Point;//在此必须对Point进行声明,如不声明将会导致第5行(void fun(Point t);)“Point”报错(无法识别的标识符)

 class Line{
public:
void fun(Point t);
//void Line::fun(Point t)//在此编译器无法获知class Point中到底有哪些成员,所以应在Point后面定义
//{
// t.x = 120;
// t.y = 130;
// t.print();
//} }; class Point{
public:
friend void Line::fun(Point t);
Point(){}
void print()
{
cout << this->x << endl;
cout << this->y << endl;
}
private:
int x;
protected:
int y;
}; void Line::fun(Point t)//应在此定义fun函数
{
t.x = ;
t.y = ;
t.print();
} int main()
{
Point test;
Line LL;
LL.fun(test);
system("pause");
return ;
}

运行结果:

c++友元函数、友元类、友成员函数

总结:关键字“friend”描述的函数就是友元函数,“friend”所在类的所有成员都可被友元函数访问。(带有关键字“friend”的类,就说明这个类有一个好朋友,他的好朋友就是关键字“friend”后面跟的那个函数或类。他的好朋友可以访问他的所有成员  )