gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 21:48:33 25 4
gpt4 key购买 nike

我有一个 ZoneDeVie 类,其中包含 Bacterie* 的 vector vector 。 Bacterie 类包含一个整数值 energie(默认设置为 10)和一个打印该值的 toString() 函数。在 ZoneDeVie 构造函数中,我构建了二维表,用 Bacterie 的默认实例填充每个单元格。然后,在我的主要方法中,我通过打印表中最后一个 BacterietoString() 进行测试。出于某种原因,它返回一个随机的、非常大的整数(通常类似于: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() 方法,然后再在 main 方法中调用它才能使其按预期运行?

最佳答案

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

这会编译并提供正确的输出。

关于C++成员变量值根据是否打印出来而变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10447856/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com