第三次作业

1.作业概述:

本次作业学习了数据的封装与分享,我便从分享这方面构思了一个问题,即用友元类来求出两点之间的距离,书上给出的例题采用的是友元函数来解决问题,因此我打算采用友元类来解决距离问题:

2.代码实现:

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

using namespace std;

class A {
public:
A(int x = 0, int y = 0) : x(x), y(y) {}
int getX() { return x; }
int getY() { return y; }
``

friend class B;

private:
int x,y;
;
};

class B {
public:
void display()
{
cout << "点的横坐标为:" << a.getX();
cout << "点的纵坐标为:" << a.getY() << endl;
}
void set(int i, int j);
double caculate(B &p1, B &p2);
private:
A a;
};

void B::set(int i, int j)
{
a.x = i;
a.y = j;
}

double B::caculate(B &p1, B&p2)
{
double a = p2.a.x - p1.a.x;
double b = p2.a.y - p1.a.y;
return static_cast<float>(sqrt(a*a + b * b));
}

int main()
{
int i, j, k, l;
B p1, p2;
cout << "请输入第一个点的横纵坐标:" << endl;
cin >> i >> j;
p1.set(i, j);
cout << "请输入第二个点的横纵坐标:" << endl;
cin >> k >> l;
p2.set(k, l);
cout << "最终的结果为:" << p1.caculate(p1, p2) << endl;
return 0;
}

利用了c的数学库来实现开根号。

3.问题感想:

在利用与书中不同的方法来解决该问题时,我明显感觉书上的解决思路明显比我更好,与其使用友元类来解决问题,不如只定义一个类,然后利用友元函数计算,代码量小而且看起来非常直观,而且友元类访问数据也不是很方便,但他的优点在于可以较少的定义第二个类的友元函数,把功能实现都放在第一个类中,方便理解。

原文地址:https://www.cnblogs.com/lqk0216/p/11605389.html