友元函数 编译不通过 第二个类中显示定义的函数不在该类里 为什么呢


#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;
}

友元函数必须要有一个本类实例对象作参数
比如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;
}

如有帮助,请点击我的回答下方的【采纳该答案】按钮帮忙采纳下,谢谢!

img

 
#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){}
  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 << c.Long(a) << endl;
 return 0;
}
您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!
PS:问答VIP年卡 【限时加赠:IT技术图书免费领】,了解详情>>> https://vip.csdn.net/askvip?utm_source=1146287632