访问全局范围内的私有变量

Thy*_*hys 3 c++ scope global-scope

在下面的代码中,全局范围中的foo函数尝试访问Box的私有变量,这些变量当然不起作用.我必须让foo函数在学校作业的地方显示代码中使用一行代码.

#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();
}
Run Code Online (Sandbox Code Playgroud)

Bri*_*ndy 9

查看friend关键字.