建立网站 用英语,咨询公司起名,个人养老金制度将推,.net开发手机网站实现外部类和外部函数存取类的私有成员和保护成员的方法。 一、友元函数 可访问类所有成员的外部函数
//求两点间的距离#xff1a;抽象点——求距离的函数
#includeiostream
#includecmath
using namespace std;
class Point{private:double x,y;publ…实现外部类和外部函数存取类的私有成员和保护成员的方法。 一、友元函数 可访问类所有成员的外部函数
//求两点间的距离抽象点——求距离的函数
#includeiostream
#includecmath
using namespace std;
class Point{private:double x,y;public:Point(double x1,double y1):x(x1),y(y1){ }void show(){cout(x,y)\tendl;}friend double Distance(Point ,Point );
};
double Distance(Point p1,Point p2){//外部函数 double dxp1.x-p2.x;//访问类中私有成员 声明为友元函数才可 double dyp1.y-p2.y;//直接访问私有成员 return sqrt(dx*dxdy*dy);
}
int main()
{Point p1(3,2),p2(9,10);//实例化两个点对象 cout两点间的距离Distance(p1,p2)endl;//调用求距离函数
}二、友元成员函数 可访问类所有成员的外部类的成员函数
//根据两点坐标差构造一个矩形类
#includeiostream
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*(lengthwidth)\t面积length*widthendl;}
};
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)\tendl;}
};
Rectangle::Rectangle(Point p1,Point p2)//通过两点位置求长宽赋值给属性(通过构造函数求矩形类的长和宽,赋给类中的属性)
:length(p1.xp2.x?p1.x-p2.x:p2.x-p1.x),
width(p1.yp2.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 友元类名;//声明友元类 小结均不具有传递性与对称性。