C ++中的私有类属性

时间:2015-04-08 18:56:33

标签: c++ private

我目前正在复习学校的课程,而且我反对这个问题。

以下代码的问题是我的x类的属性yBox是私有的,因此无法通过Foo方法访问。仍然没有告诉我为什么那么好,所以我决定向stackoverflow的优秀人员询问。

应该添加下面//Insert line of code here的代码以使我当前的程序运行?

#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();
}

3 个答案:

答案 0 :(得分:4)

这里有很多选择。如果您只允许添加一行,则可以使foo成为朋友功能:

friend bool foo(Box l, Box r);

Getters可能是更好的选择,您也可以将foo设为静态函数,但这需要三行(在定义中Box::前面添加foo在主要的地方被称为。)

答案 1 :(得分:1)

你想做什么?你想要x和y可以修改吗?如果没有,添加getX和getY方法只返回类中的值。如果你想让它们可以自由修改,就放弃OO游戏并公开它们,因为在那种情况下没有理由试图保护它们。

答案 2 :(得分:1)

使用一些get方法:

#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();
}