Reputation: 918
I'm currently reviewing a course from school and I've run against this question.
The problem with the following code is that the attributes x
and y
for my Box
class are private so can't be accessed by the Foo
method. Still the course isn't as nice as to tell me why that is so I decided to ask the fine people of stackoverflow.
What code on the //Insert line of code here
below should be added to make my current program run?
#include <iostream>
using namespace std;
class Box {
int x,y;
public:
Box(int xi, int yi)
{
x=xi;
y=yi;
}
//Insert line of code here
}
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();
}
Upvotes: 0
Views: 3498
Reputation: 304
Do it with some get methods:
#include <iostream>
using namespace std;
class Box {
int x,y;
public:
Box(int xi, int yi)
{
x=xi;
y=yi;
}
//Insert line of code here
int Box::getx(){return x;}
int Box::gety(){return y;}
}
bool foo(Box l, Box r){
return (l.get()*l.gety())>(r.getx()*r.gety());
}
int main(int argc, char* argv[])
{
Box b1(3,4), b2(1,2);
if(foo(b1,b2)) {
cout <<"b1>b2\n";
}
return cin.get();
}
Upvotes: 1
Reputation: 3651
There are a lot of options here. If you are only allowed to add one line, you could make foo
a friend function:
friend bool foo(Box l, Box r);
Getters are probably a better option, and you could make foo
a static function as well, but that would take three lines (adding Box::
in front of foo
in the definition and in main where it is called).
Upvotes: 4
Reputation: 70377
What are you trying to do? Do you want x and y to be modifiable? If not, add getX and getY methods that simply return the values from within the class. If you want them to be modifiable freely, drop the OO charade and just make them public, since there's no reason to try to protect them in that case.
Upvotes: 1