1、友元的概念:c++
一、什么是友元?web
友元是c++中的一种关系微信
友元关系发生在函数与类之间或者类与类之间编辑器
友元关系是单项的,不能传递函数

二、友元的用法:测试
在类中以friend关键字声明友元flex
类的友元能够是其它类或者具体函数ui
友元不是类的一部分this
友元不受类中访问级别的限制url
友元能够直接访问具体类的全部成员
三、友元的语法:
在类中使用friend 关键字对函数或者类进行声明:
class Test
{
double x;
double y;
friend void func(Test& t);
};
void func(Test& t)
{
}
注意:func() 全局函数是 Test 类的友元,func() 能够访问Test 类的全部成员,可是 func() 不是 Test 的成员函数。
示例代码:
#include <stdio.h>
#include <math.h>
class Test
{
double x;
double y;
public:
Test(double x,double y)
{
this->x=x;
this->y=y;
}
double getX()
{
return x;
}
double getY()
{
return y;
}
friend double func(Test& t1,Test& t2);
};
double func(Test& t1,Test& t2)
{
double ret =0;
ret = (t2.y-t1.y)*(t2.y-t1.y)+(t2.x-t1.x)*(t2.x-t1.x);
ret = sqrt(ret);
return ret;
}
int main()
{
Test t1(1,2);
Test t2(10,20);
printf("t1(%f,%f)\n",t1.getX(),t1.getY());
printf("t2(%f,%f)\n",t2.getX(),t2.getY());
printf("(t1,t2)=%f\n",func(t1,t2));
return 0;
}
输出结果:
root@txp-virtual-machine:/home/txp/add# g++ test.cpp
root@txp-virtual-machine:/home/txp/add# ./a.out
t1(1.000000,2.000000)
t2(10.000000,20.000000)
(t1,t2)=20.124612
四、友元的尴尬:
友元是为了兼顾c语言的高效而诞生的
友元直接破坏了面向对象的封装性
友元在实际开发产品中的高效是得不偿失的
友元在软件工程中已经慢慢被遗弃了
五、注意事项:
友元关系不具有传递性
类的友元能够是其它类的成员函数
类的友元能够是某个完整的类
全部的成员函数都是友元

代码测试:
#include <stdio.h>
class ClassC
{
const char* n;
public:
ClassC(const char* n)
{
this->n = n;
}
friend class ClassB;
};
class ClassB
{
const char* n;
public:
ClassB(const char* n)
{
this->n = n;
}
void getClassCName(ClassC& c)
{
printf("c.n = %s\n", c.n);
}
friend class ClassA;
};
class ClassA
{
const char* n;
public:
ClassA(const char* n)
{
this->n = n;
}
void getClassBName(ClassB& b)
{
printf("b.n = %s\n", b.n);
}
/*
void getClassCName(ClassC& c)
{
printf("c.n = %s\n", c.n);
}
*/
};
int main()
{
ClassA A("A");
ClassB B("B");
ClassC C("C");
A.getClassBName(B);
B.getClassCName(C);
return 0;
}
输出结果:
root@txp-virtual-machine:/home/txp/add# ./a.out
b.n = B
c.n = C
若是把上面屏蔽的那部分代码打开,编译就会报错(由于友元没有传递性哦):
root@txp-virtual-machine:/home/txp/add# g++ test.cpp
test.cpp: In member function ‘void ClassA::getClassCName(ClassC&)’:
test.cpp:5:17: error: ‘const char* ClassC::n’ is private
const char* n;
^
test.cpp:48:32: error: within this context
printf("c.n = %s\n", c.n);
^
六、小结:
友元是为了兼顾c语言的高效而诞生的
友元直接破坏了面向对象的封装性
友元关系不具有传递性
类的友元能够是其它类的成员函数
-
类的友元能够是某个完成的类
2、总结:
好了,今天的分享就到这里,若是文章中有错误或者不理解的地方,能够交流互动,一块儿进步。我是txp,下期见!
本文分享自微信公众号 - TXP嵌入式(txp1121518wo-)。
若有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一块儿分享。