【发布时间】:2019-07-09 18:12:49
【问题描述】:
我有使用 C++ 生成生命游戏的课程,并且必须按照讲师的指示才能通过。板的状态存储在 std::vector 中。需要一个辅助索引函数,它需要一个 x 和 y 位置来获得向量中的一维位置。需要 2 个运算符重载类,1 个(非 const)覆盖向量中的值,另一个(const)打印向量中的值。以下是目前的课程:
下面的代码编译。
在主类中,设置网格值可以正常工作,例如网格(6,1)= 1。 在特定网格处打印单元格的值不会打印该值。
我不确定问题的原因是运算符重载函数,还是ostream运算符
在主类中,我在这一行放了一个断点:
std::cout << "(6, 1) = " << grid(6,1) << std::endl;
在调试时评估grid(6,1)的值时,内容为1,所以这让我怀疑可能是我重载的ostream没有正确编程。
World.h 文件:
#include <vector>
#include <iostream>
class World {
private:
int width, height, timestep;
std::vector<char> currentCells, nextCells;
size_t index(int x, int y) const;
public:
World(int width, int height);
friend std::ostream& operator<<(std::ostream &os, const World &rhs);
friend std::ostream& headerLine(std::ostream &os, const World &rhs);
char & operator()(int x, int y);
const char& operator()(int x, int y) const;
};
World.cpp 文件:
#include "World.h"
World::World(int _width, int _height) : width(_width), height(_height), timestep(0),
currentCells(_width * _height, ' '), nextCells(_width * _height) {}
std::ostream& operator<<(std::ostream& os, const World &rhs) {
os << "timestep " << rhs.timestep << "\n";
headerLine(os, rhs);
for (auto i = 0; i < rhs.height; i++) {
os << "|";
for (auto j = 0; j < rhs.width; j++) {
if (rhs.currentCells[j + (i * rhs.width)] == ' ') {
os << ' ';
} else {
os << '0';
}
}
os << "|\n";
}
headerLine(os, rhs);
return os;
}
std::ostream& headerLine(std::ostream& os, const World &rhs) {
os << "+";
for (auto i = 0; i < rhs.width; i++) {
os << "-";
}
os << "+\n";
return os;
}
size_t World::index(int x, int y) const{
return y * width + x;
}
char& World::operator()(int x, int y) {
return currentCells[index(x, y)];
}
const char& World::operator()(int x, int y) const {
return currentCells[index(x,y)];
}
主类文件:
#include "World.h"
int main() {
World grid(10,5);
grid(6,1) = 1;
grid(5,1) = 1;
std::cout << grid << std::endl;
std::cout << "(6, 1) = " << grid(6,1) << std::endl;
return 0;
}
控制台上的预期输出:
(6, 1) = 1
控制台上的实际输出:
(6, 1) =
【问题讨论】:
-
看来
grid()返回的是空白字符,你需要将它提升为int才能看到十进制值。 -
旁注:你的
index函数被声明为char index(int x, int y) const;,而被定义为size_t World::index(int x, int y) const。 -
@AlgirdasPreidžius 刚刚更新了代码 ????????
-
@rafix07 完美,这解决了打印问题。谢谢
标签: c++