C++面向对象编程 友元函数


                                                   C++面向对象编程

 
友元函数相当于 类的封装里面开的一个小孔, 可以通过看到类里面的属性

友元函数不同于一般函数,一般成员函数访问类要通过将其数据成员设置成public 这样就破坏了类的封装, 破坏了隐藏性  但是有缘函数是不需要的

调用友元函数 直接调用, 不需要进行使用. 引用  但这函数体内 需要用“  ." 来进行引用   

具体是先看代码:
    
#include<iostream>
using namespace std;

class myclass
{
   int n ;
   public :
        myclass() {} //无参数构造函数
        myclass(int i){ n = i;}//构造函数
        friend myclass squre(myclass);    //友员函数
        void display()
        {
            cout<<" n = "<<n <<endl;
        }

};
myclass squre(myclass x)
{
    //友元函数定义
    int tmp = x.n*x.n;
    return myclass(tmp);
}
int main()
{
    myclass a(5), s1;
    s1 = squre(a);
    s1.display();
    return 0;
}

下面给出计算 点到直线的距离 的公式,要你计算出  结果    | ax + by +c|
                                                                                                        __________
                                                                                                        (a^2 +b^2)^(1/2)
 
编写程序 计算两点之间的距离
看代码 如何使用有元函数进行编程的

 代码:
 
#include<iostream>
#include<cmath>
using namespace std;
class Point
{

    public :
       double   x, y;
       Point(double  x1, double y1){ x = x1; y = y1;}

};
class Line
{
    int   a, b, c;
    public:
       Line(int a1, int  b1,int  c1){ a = a1; b = b1; c = c1;};
       friend double distance(Line l1, Point p1)
       {//为什么这要要使用友元函数呢,因为这里要访问的都一些private成员
           //下面是程序的描述部分
           double d ;
           d = abs(l1.a*p1.x + l1.b*p1.y + l1.c)/sqrt(l1.a*l1.a +l1.b*l1.b);
           return d;
       }
};
int main()
{
    Line l(1, 2,3);
    Point p(2 , 3);
    //友元函数直接调用
    cout<<" d = "<<distance(l, p)<<endl;
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wangxiaoming

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值