update
This commit is contained in:
9
practical_exercises/10_day_practice/day4/友元函数/readme.md
Normal file
9
practical_exercises/10_day_practice/day4/友元函数/readme.md
Normal file
@@ -0,0 +1,9 @@
|
||||
# 友元概念?
|
||||
友元是C++提供的一种破坏数据封装和数据隐藏的机制。
|
||||
通过将一个模块声明为另一个模块的友元,一个模块能够引用到另一个模块中本是被隐藏的信息。
|
||||
可以使用友元函数和友元类。
|
||||
为了确保数据的完整性,及数据封装与隐藏的原则,建议尽量不使用或少使用友元。
|
||||
# 如何使用?
|
||||
友元函数是在类声明中由关键字friend修饰说明的非成员函数,在它的函数体中能够通过对象名访问 private 和 protected成员
|
||||
作用:增加灵活性,使程序员可以在封装和快速性方面做合理选择。
|
||||
访问对象中的成员必须通过对象名。
|
||||
31
practical_exercises/10_day_practice/day4/友元函数/友元模块.cpp
Normal file
31
practical_exercises/10_day_practice/day4/友元函数/友元模块.cpp
Normal file
@@ -0,0 +1,31 @@
|
||||
//使用友元函数计算两点间距离
|
||||
#include <iostream>
|
||||
#include <cmath>
|
||||
using namespace std;
|
||||
class Point{
|
||||
public:
|
||||
Point(int x=0,int y=0):X(x),Y(y){}
|
||||
int GetX(){
|
||||
return X;
|
||||
}
|
||||
int GetY(){
|
||||
return Y;
|
||||
}
|
||||
friend float Distance(Point &a,Point &b);
|
||||
private:
|
||||
int X,Y;//私有数据成员
|
||||
};
|
||||
//通过将一个模块声明为另一个模块的友元,一个模块能够引用到另一个模块中本是被隐藏的信息。
|
||||
float Distance(Point &a, Point &b){
|
||||
double dx = a.X-b.X;
|
||||
double dy = a.Y-b.Y;
|
||||
return sqrt(dx*dx+dy*dy);
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
Point p1(3.0,5.0),p2(4.0,6.0);
|
||||
cout<<"两点距离为:"<<Distance(p1,p2)<<endl;
|
||||
system("pause");
|
||||
return 0;
|
||||
}
|
||||
49
practical_exercises/10_day_practice/day4/友元函数/友元类.cpp
Normal file
49
practical_exercises/10_day_practice/day4/友元函数/友元类.cpp
Normal file
@@ -0,0 +1,49 @@
|
||||
#include<iostream>
|
||||
using namespace std;
|
||||
/*
|
||||
若一个类为另一个类的友元,则此类的所有成员都能访问对方类的私有成员。
|
||||
声明语法:将友元类名在另一个类中使用friend修饰说明。
|
||||
*/
|
||||
|
||||
/*
|
||||
如果声明B类是A类的友元,B类的成员函数就可以访问A类的私有和保护数据,
|
||||
但A类的成员函数却不能访问B类的私有、保护数据。
|
||||
*/
|
||||
class A{
|
||||
friend class B;
|
||||
public:
|
||||
void Display(){
|
||||
cout<<x<<endl;
|
||||
}
|
||||
private:
|
||||
int x;
|
||||
};
|
||||
class B
|
||||
{ public:
|
||||
void Set(int i);
|
||||
void Display();
|
||||
private:
|
||||
A a;
|
||||
};
|
||||
void B::Set(int i)
|
||||
{
|
||||
a.x=i;
|
||||
}
|
||||
void B::Display()
|
||||
{
|
||||
a.Display();
|
||||
}
|
||||
|
||||
int main(int argc, char const *argv[])
|
||||
{
|
||||
B b;
|
||||
b.Set(10);
|
||||
b.Display();
|
||||
|
||||
system("pause");
|
||||
return 0;
|
||||
}
|
||||
|
||||
/*
|
||||
如果声明B类是A类的友元,B类的成员函数就可以访问A类的私有和保护数据,但A类的成员函数却不能访问B类的私有、保护数据
|
||||
*/
|
||||
Reference in New Issue
Block a user