丹东网站建设注册网站
实现外部类和外部函数存取类的私有成员和保护成员的方法。
一、友元函数
可访问类所有成员的外部函数
//求两点间的距离:抽象点——>求距离的函数
#include<iostream>
#include<cmath>
using namespace std;
class Point{private:double x,y;public:Point(double x1,double y1):x(x1),y(y1){ }void show(){cout<<"("<<x<<","<<y<<")"<<'\t'<<endl;}friend double Distance(Point &,Point &);
};
double Distance(Point &p1,Point &p2){//外部函数 double dx=p1.x-p2.x;//访问类中私有成员, 声明为友元函数才可 double dy=p1.y-p2.y;//直接访问私有成员 return sqrt(dx*dx+dy*dy);
}
int main()
{Point p1(3,2),p2(9,10);//实例化两个点对象 cout<<"两点间的距离:"<<Distance(p1,p2)<<endl;//调用求距离函数
}
二、友元成员函数
可访问类所有成员的外部类的成员函数
//根据两点坐标差构造一个矩形类
#include<iostream>
using namespace std;
class Point;//声明要访问的类
class Rectangle{//外部类 private:double length,width;public:Rectangle(double l,double w):length(l),width(w){}//直接赋长宽属性 Rectangle(Point &,Point &);//为了得到长宽,需要访问两点的位置信息-Rectangle类中的成员函数访问另一个类中的私有成员信息,将此函数在另一个类中声明为友元函数 void show(){cout<<"长:"<<length<<"\t宽:"<<width<<"\t周长:"<<2*(length+width)<<"\t面积:"<<length*width<<endl;}
};
class Point{//要访问的类 private:double x,y;public:Point(double x1,double y1):x(x1),y(y1){ }//friend Rectangle::Rectangle(Point &,Point &);//声明友元成员函数: void show(){cout<<"("<<x<<","<<y<<")"<<'\t'<<endl;}
};
Rectangle::Rectangle(Point &p1,Point &p2)//通过两点位置,求长宽赋值给属性(通过构造函数求矩形类的长和宽,赋给类中的属性)
:length(p1.x>p2.x?p1.x-p2.x:p2.x-p1.x),
width(p1.y>p2.y?p1.y-p2.y:p2.y-p1.y){}
int main()
{Point a(1,2),b(3,4);Rectangle r1(a,b);//通过点位置构造 Rectangle r2(2,3);//直接赋值构造 r1.show();r2.show();
}
注:此时外部类要定义在访问类之前,否则会报错。
三、友元类
友元类的所有成员均为该类的友元函数
friend class 友元类名;//声明友元类
小结:均不具有传递性与对称性。
