gpt4 book ai didi

c++ - 在属于类本身的方法内调用私有(private)成员

转载 作者:行者123 更新时间:2023-11-28 01:02:20 24 4
gpt4 key购买 nike

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

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”是私有(private)成员所以我不能那样调用它我认为问题出在“g.theGrid[i][j].isAlive”我试图与 Grid 类成为 friend ,但没有帮助

最佳答案

你提到了 operator<< — 它很可能是一个自由函数,因此需要将其声明为 friend能够访问私有(private)成员。

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

关于c++ - 在属于类本身的方法内调用私有(private)成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8109095/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com