#include<iostream>
#include<cmath>
using namespace std;
class Point {
private:
int x, y;
public:
Point(int x=0,int y=0):x(x),y(y){}
int getX()
{
return x;
}
int getY()
{
return y;
}
friend double line(Point& a, Point& b)
{
return sqrt(pow(a.getX() - b.getX(), 2) + pow(a.getY() - b.getY(),2));
}
};
class showPoint {
private:
int xx, yy;
public:
showPoint(int xx=0,int yy=0):xx(xx),yy(yy){}
friend int Long(Point& a)
{
return sqrt(a.getX() * a.getX() + a.getY() * a.getY());
}
};
int main()
{
Point a(3, 4);
Point b(5, 3);
cout << line(a, b) << endl;
showPoint c;
cout << Long(a) << endl;
return 0;
}
友元函数 编译不通过 第二个类中显示定义的函数不在该类里 为什么呢
- 写回答
- 好问题 0 提建议
- 关注问题
- 邀请回答
-
3条回答 默认 最新
CSDN专家-天际的海浪 2022-06-03 00:35关注友元函数必须要有一个本类实例对象作参数
比如showPoint 类的友元函数必须要有一个showPoint 类实例对象作参数friend int Long(Point& a, showPoint &c)加上, showPoint &c你题目的解答代码如下:
#include<iostream> #include<cmath> using namespace std; class Point { private: int x, y; public: Point(int x=0,int y=0):x(x),y(y){} int getX() { return x; } int getY() { return y; } friend double line(Point& a, Point& b) { return sqrt(pow(a.getX() - b.getX(), 2) + pow(a.getY() - b.getY(),2)); } }; class showPoint { private: int xx, yy; public: showPoint(int xx=0,int yy=0):xx(xx),yy(yy){} friend int Long(Point& a, showPoint &c) { return sqrt(a.getX() * a.getX() + a.getY() * a.getY()); } }; int main() { Point a(3, 4); Point b(5, 3); cout << line(a, b) << endl; showPoint c; cout << Long(a,c) << endl; return 0; }如有帮助,请点击我的回答下方的【采纳该答案】按钮帮忙采纳下,谢谢!
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报 编辑记录