Access private variable in global scope

In this code below, the foo function in the global scope tries to access Box private variables, which of course doesn't work. I need the foo function to work with one line of code in a place showing the code for the school assignment.

#include <iostream>

using namespace std;
class Box {
      int x,y;

      public:
             Box(int xi,int yi) {x=xi;y=yi;}
             // One line of code to make foo(Box, Box) work
};

bool foo(Box l,Box r) {return (l.x*l.y)>(r.x*r.y);}

int main(int argc, char* argv[]) {
    Box b1(3,4),b2(1,2);

    if (foo(b1,b2)) cout << "b1>b2\n";

    return cin.get();
}
+3
source share
4 answers

Declare fooas friend functioninsideBox

   #include<iostream>

   class Box {
     int x,y;

     public:
         Box(int xi,int yi) :x(xi),y(yi){}// Always use initializer list for initializing data members, i.e. prefer initialization over assignment

         friend bool foo(Box,Box);// friend functions can access private members
   };

   bool foo(Box l,Box r)       // friend keyword not to be written while defining the function
   {return (l.x*l.y)>(r.x*r.y);}

   int main(int argc, char* argv[]) {
      Box b1(3,4),b2(1,2);

      if (foo(b1,b2)) std::cout << "b1>b2\n";

     return std::cin.get();
   }
+1
source

Find the keyword friend .

+9
source

, . , Box , ().

Secondly, since this is a school assignment, I think that the solution should have been mentioned in the classroom: this can be achieved through the announcement friend.

+3
source

In addition to other answers related to friends, the best answer for a long-term (albeit not a one-line change) would be for Box to overload the corresponding comparison operators.

0
source

Source: https://habr.com/ru/post/1751012/


All Articles