C++中友元函数访问不了类中的私有成员

#include <iostream>
#include <math.h>
using namespace std;
class Point {
private:
    float x;
    float y;
public:
    Point(float X = 0.0f, float Y = 0.0f) :x(X), y(Y) {
    };
    float show();
    friend Point operator -(Point& t, Point& t1);
};
float Point::show() {
    cout << x << "," << y << endl;
    return 0;
}
Point operator +(Point& t, Point& t1) {
    return sqrt((t.x - t1.x) * (t.x - t1.x) + (t.y - t1.y) * (t.x - t1.y));
}
int main() {
    Point t, t1(3, 4), t3;
    t.show();
    t3 = t - t1;
    cout << t3.show() << endl;
}

题目要求

(1)编写构造函数,用于完成点类对象初始化。默认初始值为(0,0)。

(2)编写成员函数show(),用于显示平面点的坐标值。

(3)重载减法运算符为非成员函数,用于计算当前点与另一点之间的距离计算。

(4)编写main()函数完成上述类的测试应用。

vs2019错误报告,不知道错在哪里

1.去掉using namespace std;后面的cout和endl改成std::cout和std::endl

2.友元函数实现的时候写错了(第18行),应该是-号,不是+号

代码修改如下:

#include <iostream>
#include <math.h>
//using namespace std;

using std::cin; using std::cout; using std::ostream; using std::istream; using std::endl;
class Point {
private:
	float x;
	float y;
public:
	Point(float X = 0.0f, float Y = 0.0f) :x(X), y(Y) {
	};
	float show();
	friend Point operator -(Point& t, Point& t1);
};
float Point::show() {
	std::cout << x << "," << y << std::endl;
	return 0;
}
Point operator -(Point& t, Point& t1) { //+
	return sqrt((t.x - t1.x) * (t.x - t1.x) + (t.y - t1.y) * (t.x - t1.y));
}
int main() {
	Point t, t1(3, 4), t3;
	t.show();
	t3 = t - t1;
	std::cout << t3.show() << std::endl;
}

 

你没有实现友元函数啊。。

friend Point operator -(Point& t, Point& t1);

 

 

Point operator +(Point& t, Point& t1) {

return sqrt((t.x - t1.x) * (t.x - t1.x) + (t.y - t1.y) * (t.x - t1.y));

}

减法没有实现哦,只有定义。。

Point operator +(Point& t, Point& t1) {

应该是Point operator -(Point& t, Point& t1) {吧

+改成-就好了

您好,我是有问必答小助手,您的问题已经有小伙伴解答了,您看下是否解决,可以追评进行沟通哦~

如果有您比较满意的答案 / 帮您提供解决思路的答案,可以点击【采纳】按钮,给回答的小伙伴一些鼓励哦~~

ps:问答VIP仅需29元,即可享受5次/月 有问必答服务,了解详情>>>https://vip.csdn.net/askvip?utm_source=1146287632