2676 3-7 类的友元函数的应用

桃扇骨 2022-07-16 07:49 20阅读 0赞

3-7 类的友元函数的应用

  1. #include<iostream>
  2. #include<cmath>
  3. using namespace std;
  4. int n;
  5. class point
  6. {
  7. private:
  8. double x;
  9. double y;
  10. public :
  11. point (){x=0;y=0;}
  12. point (double a,double b){x=a;y=b;}
  13. void display();
  14. void display1();
  15. friend void display2(point &p1,point &p2);
  16. };
  17. void point::display()
  18. {
  19. cout << "The first point is the coordinate:X=" << x << ",Y=" << y << endl;
  20. }
  21. void point::display1()//有无friend 的区别
  22. {
  23. cout << "The second point is the coordinate:X=" << x << ",Y=" << y << endl;
  24. }
  25. void display2(point &p1,point &p2)//有无friend 的区别
  26. {
  27. double c;
  28. c=sqrt((p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y));
  29. cout << "The distance between the two points is:" <<c<< endl;
  30. }
  31. int main()
  32. {
  33. double x1,x2,y1,y2;
  34. cin>>x1>>y1>>x2>>y2;
  35. point p1(x1,y1);
  36. point p2(x2,y2);
  37. p1.display();
  38. p2.display1();
  39. display2(p1,p2);
  40. }

发表评论

表情:
评论列表 (有 0 条评论,20人围观)

还没有评论,来说两句吧...

相关阅读

    相关 函数

    操作符重载是C++的强大特性之一 操作符重载的本质是通过函数扩展操作符的语义 operator关键字是操作符重载的关键 friend关键字可以对函数或类开发访问权限 操

    相关 函数

    友元函数可能会破环原类的私有属性: 声明有缘函数关键字;friend 在实现类之间数据共享时,减少系统开销,提高效率。如果类A中的函数要访问类B中的成员(例如:智能指针类的

    相关 函数

    采用类的机制后实现了数据的隐藏与封装,类的数据成员一般定义为私有成员,成员函数一般定义为公有的,依此提供类与外界间的通信接口。但是,有时需要定义一些函数,这些函数不是类的一部分