ZoneDeVie
のベクトルのベクトルを含むクラスがありBacterie*
ます。このBacterie
クラスには、int値energie
(デフォルトでは10に設定)とtoString()
値を出力する関数が含まれています。コンストラクターで、ZoneDeVie
2Dテーブルを作成し、各セルにデフォルトのインスタンスを入力しますBacterie
。次に、私のメインの方法では、テーブルtoString()
の最後のを印刷してテストしBacterie
ています。何らかの理由で、ランダムで不愉快に大きいint(通常は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()メソッドを呼び出して、期待どおりに動作させる必要があるのでしょうか。