友元关键字是friend,也就是朋友的意思。友元必须另一个类中声明,函数或类自己说是别人的友元不行。
为什么要有友元friend?
有时在写代码时,类外要访问私有成员,这种情况下就只能声明成友元,不然无法防问类内私有成员。
C++支持两种友元:友元函数、友元类。
友元函数:
语法:friend 返回类型 函数名(参数表)
1 2 3 4 |
void fun(A c1) { cout<<c1.x<<c1.y<<endl; } |
fun函数访问类内私有成员,在A类中要将fun函数声明成友元函数。不然无法通过编译。
友元函数例代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
//梁笔记 //zouzhongliang.com #include <iostream> using namespace std; class A { private: double x,y; public: A(){ x = 0; y = 0; } ~A(){ } friend void fun(A c1); //声明成friend }; void fun(A c1) { cout<<c1.x<<c1.y<<endl; } int main() { A c1; fun(c1); return 0; } |
友元类?
语法:friend class 类名
A类在B类中声明成友元类,A类就可以访问B类中的私有成员。
具体的来写段友元类代码,看了就会明白:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
//梁笔记 //zouzhongliang.com #include <iostream> using namespace std; class A; class B { private: double c,d; public: B(){ c = 0; d = 0; } ~B(){ } friend class A; //友元类 }; class A { private: double x,y; B b; public: A(){ x = 0; y = 0; } ~A(){ } void print(){ cout<<x<<y<<endl; cout<<b.c<<b.d<<endl; //直接访问B中的私有成员 } }; int main() { A c1; c1.print(); return 0; } |
注意:友元概念为编程带来了方便,但不建议大家经常用。这样另一个类可以直接修改私有成员变量,总归不是很安全。可以在设计类时规划好,尽量不要友元实现。
Well spoken certainly! . diflucan for yeast infection
Thank you! A lot of knowledge.
modafinil side effects
Helpful data. Regards. side effects of viagra
Thank you, I enjoy this! fda cbd hearing
Nicely put. Thanks. canadadrugsonline
Incredible quite a lot of great data! Provigil Modafinil Buy Online Uk
Amazing many of very good advice. mexican pharmacies shipping to usa
Thanks a lot! A lot of facts!
top rated online canadian pharmacies
You revealed that really well! inderal
With thanks! I value it. canada pharmaceutical online ordering
Kudos! Lots of material!
provigil side effects
You’ve made your point extremely nicely!! generic viagra prices
Really quite a lot of fantastic material! prinivil
Many thanks! I value it. canadian online pharmacies
Tips well considered.. modafinil dosage
Beneficial tips. Thank you. canada drugs
Thanks a lot, Lots of advice!
celexa generic
Thanks a lot, Numerous advice.
is viagra safe