C++ 成员变量值根据是否打印出来而变化
C++ Member Variable value changes based on whether or not it is printed out
>我有一个类ZoneDeVie
,其中包含Bacterie*
向量的向量。Bacterie
类包含一个 int 值energie
(默认情况下设置为 10)和一个打印该值的 toString()
函数。在 ZoneDeVie
构造函数中,我构建了 2D 表,并用 Bacterie
的默认实例填充每个单元格。然后,在我的主要方法中,我通过打印表中最后一个Bacterie
的toString()
进行测试。出于某种原因,它返回一个随机的、令人讨厌的大 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;
};
这将编译并提供正确的输出。
此代码存在几个问题。
-
目前尚不清楚
Bacterie
的默认构造函数是做什么的。 -
目前尚不清楚
ZoneDeVie::tableau
是什么以及如何使用局部向量bacvec
。
目前 尚不清楚如何定义类
ZoneDeVie
的复制构造函数和operator=
(两者都在main()
中使用)。似乎表中的所有条目都使用指向同一
Bacterie
bac
的指针进行初始化
- 如何循环打印顶点结构
- 为什么在popback()操作之后,它仍然打印完整的矢量
- 如何在c++中打印目录
- 有一个打印语句的函数是一种糟糕的编程实践吗
- 在线编译器中的分段C++没有打印消息
- 在C++中打印指向不同基元数据类型的指针的内存地址
- 这个指针和内存代码打印是什么?我不知道是打印垃圾还是如何打印我需要的值
- C++取消引用指针.为什么会发生变化
- 为什么在读取文件大小时文件IO速度会发生变化
- 如何将结构插入到集合中并打印集合的成员
- 在循环C++中指定字符串之后,不会打印该字符串
- 以螺旋方式打印矩阵的程序.(工作不好)
- 从控制台中删除最后打印的元素
- 如何使用Crypto++并为RSA返回可打印的字节/字符数组
- 如何仅使用对象名称打印特定于对象的成员
- 回溯C++不打印函数,因此文件
- 在一定长度后从数组中打印时缺少整数
- 声明双重给它一个值0,但打印结果意外变化
- 在递归函数中打印一次变量,该变量会随着每次递归而不断变化
- C++ 成员变量值根据是否打印出来而变化