我有一个ZoneDeVie
包含向量向量的类Bacterie*
。该类Bacterie
包含一个 int 值energie
(默认设置为 10)和一个toString()
打印该值的函数。在ZoneDeVie
构造函数中,我构建了 2D 表,用默认的 a 实例填充每个单元格Bacterie
。然后,在我的主要方法中,我通过打印表格toString()
中的最后一个来进行测试。Bacterie
由于某种原因,它返回一个随机的、令人讨厌的大整数(通常类似于:3753512);但是,如果我在 ZoneDeVie 的toString()
构造函数中调用 Bacterie 的方法,则 main 方法将正确打印出来。
#include <iostream>
#include <sstream>
#include <vector>
using namespace std;
class Bacterie {
public:
Bacterie() { this->energie = 10; }
string toString() {
stringstream ss;
ss << "Energie: " << this->energie;
return ss.str();
}
protected:
int energie;
};
class ZoneDeVie {
public:
ZoneDeVie(int width, int height) {
Bacterie* bac = new Bacterie();
// without this [following] line, the call to `toString`
// in the main method will return an obnoxiously-large value
//bac->toString();
for (int i=0; i<height; i++) {
vector<Bacterie*> bacvec = vector<Bacterie*>();
this->tableau.push_back(bacvec);
for (int j=0; j<width; j++) {
this->tableau[i].push_back(bac);
}
}
}
vector<vector<Bacterie*> > tableau;
};
int main(int argc, char *argv[]) {
int x,y;
x = 9; y = 39;
ZoneDeVie zdv = ZoneDeVie(10,40);
cout << "zdv(" << x << "," << y << ") = " << zdv.tableau[x][y]->toString();
return 0;
}
输出(在 ZoneDeVie 的构造函数中调用“toString()”): zdv(9,39) = Energie: 10
输出(在 ZoneDeVie 的构造函数中没有调用“toString()”): zdv(9,39) = Energie: 4990504
为什么我需要先调用我的 toString() 方法才能在 main 方法中调用它以使其行为符合预期?