C++ 成员变量值根据是否打印出来而变化

C++ Member Variable value changes based on whether or not it is printed out

本文关键字:变化 打印 是否 成员 变量值 C++      更新时间:2023-10-16

>我有一个类ZoneDeVie,其中包含Bacterie*向量的向量。Bacterie类包含一个 int 值energie(默认情况下设置为 10)和一个打印该值的 toString() 函数。在 ZoneDeVie 构造函数中,我构建了 2D 表,并用 Bacterie 的默认实例填充每个单元格。然后,在我的主要方法中,我通过打印表中最后一个BacterietoString()进行测试。出于某种原因,它返回一个随机的、令人讨厌的大 int(通常类似于:3753512);但是,如果我在 ZoneDeVie 的构造函数中调用 Bacterie 的 toString() 方法,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() 方法之前,我需要调用它才能让它按预期运行?

交换 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的默认构造函数是做什么的。

  2. 目前尚不清楚ZoneDeVie::tableau是什么以及如何使用局部向量bacvec

  3. 目前
  4. 尚不清楚如何定义类 ZoneDeVie 的复制构造函数和operator=(两者都在 main() 中使用)。

  5. 似乎表中的所有条目都使用指向同一Bacterie bac的指针进行初始化