在属于类本身的方法中调用私有成员

时间:2011-11-13 02:08:34

标签: c++

我在实现一个类时遇到了这个问题:

class Cell {
     bool isAlive;
     int numNeighbours;
     //...omit irrelavent private members



     public:
         Cell();  // Default constructor
         ~Cell(); // Destructor


      void setLiving();   

     ....         
    };
    void Cell::setLiving(){
         isAlive=true;
       }


 class Grid{...
  friend std::ostream& ::operator(std::ostream& out, const Grid &g);
  };//...omit

 std::ostream& ::operator<<(std::ostream &out, const Grid &g){
 int i,j;
 for(i=0;i<g.gridSize;i++){
   for(j=0;j<g.gridSize;j++){
         if(**g.theGrid[i][j].isAliv*e*) out<<"X";
         else out<<"_";
    }
    out<<endl;
   }
    return out;
  }

编译器说“isAlive”是私人会员所以我不能这样称呼它 我认为问题出在“g.theGrid [i] [j] .isAlive” 我试图将网格格式化,但它没有帮助

3 个答案:

答案 0 :(得分:0)

类成员isAlive是私有的,因此操作员没有权限访问它,你需要在Cell的定义体中放置一个朋友声明。

class Cell {
friend std::ostream& operator<<(std::ostream&, const Cell&);
// ...

};

答案 1 :(得分:0)

这一行

if(**g.theGrid[i][j].isAlive) out<<"X"

访问私人会员'isAlive'。我假设theGrid是Cell对象的二维数组。您需要定义getLiving()方法。然后在这里使用它。

答案 2 :(得分:-1)

isAlive是私有的,将其声明为公开......

EDIT1:

class Cell {
public:
   bool isAlive;

更新

  • 班级的私人成员只能从同一班级的其他成员或其朋友那里访问。
  • 受保护的成员可以从同一个班级的成员和他们的朋友那里访问,也可以从派生类的成员访问。
  • 最后,可以从对象可见的任何地方访问公共成员。