C++类具有封装和信息隐蔽的特性,只有类中的成员函数才能访问类的私有成员,类外无法访问。
存在问题:当需要多次存取类的数据成员时,会出现相应的成员函数被多次调用的情况。由于参数传递、类类型检查和安全性检查等都需要时间开销,从而将影响程序的运行效率。但如果将这些数据成员都定义为公有,破坏了隐蔽的特性。
解决办法:友元函数。
友元函数在类中声明,但是不属于该类的成员函数。如果要在它的函数体中操纵类的数据成员,必须通过参数传递该类的对象来进行。
//友元函数
#include<iostream>
#include<cmath>
using namespace std;
class CPoint
{
public:
CPoint(double xx=0,double yy=0);
double getX();
double getY();
friend double fDist(CPoint *p1,CPoint *p2);
private:
double x,y;
};
CPoint::CPoint(double xx,double yy)
{
x=xx;
y=yy;
}
double CPoint::getX()
{
return x;
}
double CPoint::getY()
{
return y;
}
double fDist(CPoint *p1,CPoint *p2)//指针
{
double x=double(p1->x-p2->x);
double y=double(p1->y-p2->y);
return sqrt(x*x+y*y);
}
double fDist_s(CPoint *p1,CPoint *p2)//非友元,不能通过CPoin类对象指针直接访问所指对象的私有数据成员x与y
{
double x=double(p1->getX()-p2->getX());//因为是非友元,所以只能通过getX(),getY()来访问私有数据成员了
double y=double(p1->getY()-p2->getY());
return sqrt(x*x+y*y);
}
int main()
{
CPoint *p1=new CPoint(1,2);
CPoint *p2=new CPoint(2,4);
cout<<"通过友元函数:";
cout<<"the distance is:"<<fDist(p1,p2)<<endl;
cout<<"通过普通函数:";
cout<<"the distance is:"<<fDist_s(p1,p2)<<endl;
delete p1;
delete p2;
system("pause");
return 0;
}
由于定义了友元函数fDist(),可以通过CPoint类对象指针p1,p2直接访问所指对象的私有数据成员x和y。
由于fDist_s()非友元,不能通过CPoin类对象指针直接访问所指对象的私有数据成员x与y,所以只能通过getX(),getY()来访问私有数据成员了。
//友元类
#include<iostream>
#include<string>
using namespace std;
class B;//先声明类B
class A
{
private:
friend class B;
char *name;
int age;
public:
A(char *str,int n);
};
class B
{
public:
void show(A *x);
};
A::A(char *str,int n)
{
name=new char[strlen(str)+1];
strcpy(name,str);
age=n;
}
//void B::show(A x)
void B::show(A *x)//由于类A把类B声明为它的友元类,所以类B的成员函数相应的都成为了类A的友元函数
{
cout<<"姓名:"<<x->name<<endl;
cout<<"年龄:"<<x->age<<endl;
}
int main()
{
//A a("兰智辉",21);
A *a=new A("兰智辉",21);
B b;
b.show(a);
system("pause");
return 0;
}
由于类A把类B声明为它的友元类,所以类B的成员函数相应的都成为了类A的友元函数,可以自由的访问类A的私有数据成员name和age。