avr39ripe

cppPointDistanceFriendFunction

Aug 4th, 2021
459
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <iostream>
  2.  
  3. class ClassB
  4. {
  5.     void bFunction() {/* тело функции */};
  6. };
  7.  
  8. class ClassName
  9. {
  10.     // определение класса
  11.  
  12.     friend void nonMemberFunction(); // 1
  13.     friend void ClassB::bFunction(); // 2
  14. };
  15.  
  16. void nonMemberFunction() {/* тело функции */ }
  17.  
  18. class Point
  19. {
  20.     int x;
  21.     int y;
  22. public:
  23.     Point() = default;
  24.     Point(int pX, int pY) : x{ pX }, y{ pY } {}
  25.     Point& setX(int pX) { x = pX; return *this; }
  26.     Point& setY(int pY) { y = pY; return *this; }
  27.     int getX()const { return x; }
  28.     int getY()const { return y; }
  29.     void showPoint() const
  30.     {
  31.         std::cout << '(' << x << ',' << y << ')';
  32.     }
  33.     friend double distance(const Point& p1, const Point& p2);
  34. };
  35.  
  36. double distance(const Point& p1, const Point& p2)
  37. {
  38.     auto xLength{ p2.x - p1.x };
  39.     auto yLength{ p2.y - p1.y };
  40.     return sqrt(xLength * xLength + yLength * yLength);
  41. }
  42.  
  43. int main()
  44. {
  45.     Point p1{ 5,5 };
  46.     Point p2{ 10,10 };
  47.  
  48.     std::cout << "Distance between p1 and p2 is: " << distance(p1, p2) << '\n';
  49.  
  50.     return 0;
  51. }
RAW Paste Data