1、友元函数的使用
实例:求点到点的距离和点到直线的距离。定义两个类,一个坐标点类,一个直线类
#include "stdafx.h" #include <iostream> #include <cmath> using namespace std; class Line; class Point; float distance_PointToPoint (Point & P,Point & Q); float distance_PointToLine(Point &P,Line &L); class Point//坐标点类(x,y) { private: float x; float y; public: Point (float x0=0.0,float y0=0.0) { x=x0; y=y0; } friend float distance_PointToPoint (Point & P,Point & Q);//说明友元函数 friend float distance_PointToLine(Point& P,Line& L);//说明友元函数 }; class Line //直线类ax+by+c=0 { private: float a; float b; float c; public: Line(float a0,float b0,float c0) { a=a0; b=b0; c=c0; } friend float distance_PointToLine(Point& P,Line& L);//友元函数的声明 }; float distance_PointToPoint (Point & P,Point & Q)//求两点的距离 { return (P.x-Q.x)*(P.x-Q.x)+(P.y-Q.y)*(P.y-Q.y); } float distance_PointToLine(Point& P,Line& L)//求点到直线的距离 { return (L.a *P.x +L.b *P.y +L.c)/sqrt(L.a *L.a +L.b *L.b ); } int _tmain(int argc, _TCHAR* argv[]) { Point A(0.0,0.0); Point B(3.0,4.0); Line L(1,2,5); float distance1,distance2; distance1=distance_PointToPoint(A,B); distance2=distance_PointToLine (A,L); cout<<distance1<<endl <<distance2<<endl; return 0; }
2、友元类的使用
实例:编写一个栈,实现入栈和出栈。定义两个类,节点类(包含数据data和指向上一个节点的指针和栈类(包含栈的头结点top)
#include "stdafx.h" #include<iostream> using namespace std; class Stack; class stackNode; class stackNode { private: int data; stackNode* pre; public: stackNode(int d,stackNode* p) { data=d; pre=p; } friend class Stack;//说明友元类 }; class Stack { private: stackNode* top; public: Stack(){ top=NULL; } void push(int i) { stackNode* temp=new stackNode(i,top); top=temp; } int pop() { if(top) { stackNode* temp =top; top=top->pre; int value=temp->data ; delete temp; return value; } else { cout<<"stack is null"<<endl; return 0; } } }; int _tmain(int argc, _TCHAR* argv[]) { Stack s; s.push(6); s.push (3); s.push(1); s.push (5); for(int i=0;i<=4;i++) { cout<<s.pop()<<endl; } return 0; }