友元、友元函数、友元类

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;
}

转载于:https://www.cnblogs.com/marinna/archive/2012/08/20/2648192.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值