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