C ++ Member variable variable values ​​depending on whether it prints

I have a class ZoneDeViecontaining a vector of vectors Bacterie*. The class Bacteriecontains an int value energie(default 10) and a function toString()that prints this value. In the constructor, ZoneDeVieI create a 2D table, populating each cell with a default instance Bacterie. Then, in my main method, I test by printing the toString()latter Bacteriein a table. For some reason, it returns a random, nasty big int (usually something like: 3753512); however, if I call the Bacterie method toString()in the ZoneDeVie constructor, the main method will print correctly.

#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;
}

output (with toString () "in the constructor of ZoneDeVie): zdv(9,39) = Energie: 10

( toString() " ZoneDeVie): zdv(9,39) = Energie: 4990504

toString(), , , ?

+3
2

for . width, height:

class ZoneDeVie {
public:
    ZoneDeVie(int width, int height) {
        Bacterie* bac = new Bacterie();

        for (int i=0; i<width; i++) {
            vector<Bacterie*> bacvec = vector<Bacterie*>();
            this->tableau.push_back(bacvec);
            for (int j=0; j<height; j++) {
                this->tableau[i].push_back(bac);
            }
        }
    }
    vector<vector<Bacterie*> > tableau;
};

.

+1

.

  • , Bacterie.

  • , ZoneDeVie::tableau bacvec.

  • , operator= ZoneDeVie ( main()).

  • , Bacterie bac

+1

All Articles