C++第三次作业

C++第三次作业

友元函数,上课老师提出一个问题如何求两点之间的距离。利用面向对象的编程思想,那么首先得定义一个类来描述点。

class Point {
public:
	Point(int x = 0, int y = 0) :x(x), y(y) {//构造函数
		count++;
	};
	Point(Point &p)
	{
		x = p.x;
		y = p.y;
		count++;
	}
	~Point(){count--;}
	int GetX() { return x; }
	int GetY() { return y; }
	static void showCount();
private:
	int x, y;
	static int count;

};

接着来写一个类Line来操作点求距离:

class Line {
public:
	void myPoint(Point X, Point Y)
	{
		this->X = X;
		this->Y= Y;
	}
	//没有使用构造函数使用了赋值的方法给Line数据
	double XGet(Point X, Point Y)
	{
		return (X.GetX() - Y.GetX())*(X.GetX() - Y.GetX());
	}
	double YGet(Point X, Point Y)
	{
		return (X.GetY() - Y.GetY())*(X.GetY() - Y.GetY());
	}
	double GetP()
	{
		return XGet(X, Y) - YGet(X, Y);
	}
	int  GetL()
	{
		cout<< sqrt(GetP())<<endl;
		return sqrt(GetP());
	}
private:
	Point X, Y;

};

上面的计算方式非常繁琐。在main函数里面定义两个类来计算线段长度。
之后课程里面我们学习了友元函数 ,函数声明时在函数前面加上一个friend关键字。友元函数是在类中用关键字frined修饰的非成员函数,友元函数可以是一个普通的函数,也可以是其他类的成员函数,虽然他不是本类的成员函数,但是在他的函数体中可以通过对象名访问类的私有和保护成员

#include"pch.h"
#include<iostream>

#include<cmath>
using namespace std;
class Point {
public:
	Point(int x = 0, int y = 0):x(x), y(y) {}
	int getX() { return x;}
	int getY() { return y;}
	friend float dist(Point &p1, Point &p2);
private:
	int x, y;

};
float dist(Point &p1, Point &p2) {
	double x = p1.x - p2.x;
	double y = p1.y - p2.y;
	return static_cast<float>(sqrt(x*x + y * y));
}
int main()
{
	Point myp1(1, 1), myp2(4, 5);
	cout << "距离是" << dist(myp1, myp2) << endl;
}

两次运行结果是完全一致的,很明显使用友元函数的来处理这个问题是非常简单的。但是同时也得注意了:友元函数波坏了类的封装性,降低了该累的可维护性和安全性

原文地址:https://www.cnblogs.com/Eldq/p/11602045.html