C++中使用friend class结合parameterized constructor计算两点距离报错问题
问题:友元类实现两点距离计算报错
我需要计算两点间的距离,设计了point类:
- 带参构造函数
point(int a, int b)给私有成员x、y赋值 displayPoint()成员函数打印坐标格式(x,y)- 将
dist类声明为友元类,打算让dist类通过接收两个point对象的构造函数计算并输出距离,但代码报错。
错误代码如下:
// Parameterized Constructor using Friend Class Example :- #include <iostream> #include <cmath> using namespace std; class point { int x, y; friend class dist; public: point(int a, int b) { x = a; y = b; } void displayPoint() { cout << "The Point is : (" << x << "," << y << ")" << endl; } }; class dist // shows error here { public: void dist(point p1, point p2) { int x_diff = (p2.x - p1.x); int y_diff = (p2.y - p1.y); int diff = sqrt(pow(x_diff, 2) + pow(y_diff, 2)); cout << "The difference is : " << diff << endl; } }; int main() { point p(1, 2); point q(4, 6); point c(1, 1); point d(1, 1); point e(1, 0); point f(70, 0); dist(p, q); dist(c, d); dist(e, f); return 0; }
我尝试移除dist类,把dist()改成友元函数后代码能正常运行,可行代码如下:
void dist(point p1, point p2) { int x_diff = (p2.x - p1.x); int y_diff = (p2.y - p1.y); int diff = sqrt(pow(x_diff, 2) + pow(y_diff, 2)); cout << "The difference is : " << diff << endl; }
错误原因分析
- 构造函数语法错误:构造函数不能有返回值类型,你给
dist类的构造函数加了void修饰,违反了C++语法规则——构造函数必须与类同名且无返回值(包括void)。 - 构造函数调用方式错误:
main中dist(p, q)的写法不合法,构造函数是用来创建类对象的,正确写法应为dist obj(p, q);,且用构造函数执行计算输出不符合代码职责分离原则。 - 精度丢失问题:
sqrt()和pow()函数返回double类型,用int类型的diff接收会截断小数部分,导致距离计算精度丢失。
修正方案1:修复友元类的写法
如果坚持用友元类实现,修正后的代码如下:
#include <iostream> #include <cmath> using namespace std; class point { int x, y; friend class dist; public: point(int a, int b) : x(a), y(b) {} void displayPoint() { cout << "The Point is : (" << x << "," << y << ")" << endl; } }; class dist { public: // 构造函数无返回值,直接执行计算逻辑 dist(point p1, point p2) { int x_diff = p2.x - p1.x; int y_diff = p2.y - p1.y; // 用double存储避免精度丢失 double diff = sqrt(pow(x_diff, 2) + pow(y_diff, 2)); cout << "The distance is : " << diff << endl; } }; int main() { point p(1, 2); point q(4, 6); point c(1, 1); point d(1, 1); point e(1, 0); point f(70, 0); // 通过创建dist对象触发构造函数计算 dist obj1(p, q); dist obj2(c, d); dist obj3(e, f); return 0; }
修正方案2:使用友元函数(更简洁)
友元函数的方式更符合场景需求——仅需计算距离,不需要额外维护类对象,修正精度问题后的代码如下:
#include <iostream> #include <cmath> using namespace std; class point { int x, y; // 声明友元函数 friend void dist(point p1, point p2); public: point(int a, int b) : x(a), y(b) {} void displayPoint() { cout << "The Point is : (" << x << "," << y << ")" << endl; } }; // 实现友元函数,用double存储距离 void dist(point p1, point p2) { int x_diff = p2.x - p1.x; int y_diff = p2.y - p1.y; double diff = sqrt(pow(x_diff, 2) + pow(y_diff, 2)); cout << "The distance is : " << diff << endl; } int main() { point p(1, 2); point q(4, 6); point c(1, 1); point d(1, 1); point e(1, 0); point f(70, 0); dist(p, q); dist(c, d); dist(e, f); return 0; }
内容的提问来源于stack exchange,提问作者Aslam Sha
相关产品推荐
相关产品推荐

