a'ゞ 遇见 2021-06-06 19:55 采纳率: 100%
浏览 77
已采纳

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错误报告,不知道错在哪里

  • 写回答

4条回答 默认 最新

  • qfl_sdu 2021-06-06 20:06
    关注

    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;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 基于单片机的靶位控制系统
  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错