在C++中使用全局变量进行练习
Exercise with global variables in C++
我在练习C++语言时遇到了一些麻烦: 该练习包括: 有一辆有 55 个座位的公共汽车供旅行者使用,我必须能够从这辆公共汽车中添加、编辑和删除旅客。
到目前为止,我的代码可以工作,但我不知道为什么当我添加或显示变量时没有正确存储在我的数组中。
#include <iostream>
using namespace std;
//Clase que representa un objeto de un viejero
class Viajero {
public:
string nombre;
};
//declaración de las funciones
void anadirViajero();
void mostraViajeros();
//declaración de las variables globales
static Viajero autobus[55];
int main() {
anadirViajero();
mostraViajeros();
return 0;
}
void anadirViajero(){
string nombre;
bool check = false;
for(Viajero viajero : autobus){
if(viajero.nombre == "" && check == false){
cout<<"Nombre Viajero: ";
cin>>nombre;
viajero.nombre = nombre;
check = true;
}
}
}
void mostraViajeros(){
int count = 0;
for(Viajero viajero : autobus){
count++;
cout<<"Nombre: ";
cout<<viajero.nombre;
}
cout<<"Total de Viajeros: "<<count;
}
我不确定我的全局变量是否是解决此练习的正确方法。我试图在声明中放置静态,但仍然不存储值。
这里
:if(viajero.nombre == "" && check == false){
cout<<"Nombre Viajero: ";
cin>>nombre;
viajero.nombre = nombre;
check = true;
}
不正确,一旦您添加 1 个用户,您将标志检查设置为true
,这阻止了广告新viajero的条件
如果 Viajero 的状态是否为已检查,则应在类中定义
喜欢:
class Viajero {
public:
string nombre;
bool check;
};
除了你只会读一个名字的事实(正如 ΦXocę 웃 Пepeúpa ツ 所指出的那样(,你还有另一个问题:你的行viajero.nombre = nombre;
为一个Vialero
对象设置名称,它完全本地到 for 循环,并且从不为数组的成员分配任何东西。
要解决此问题,请将"迭代器"变量设置为对数组的引用,如下所示(请注意Viajero
后面的&
符号(:
for (Viajero& viajero : autobus) { // viajero MUST be a REFERENCE if you want to change the array element(s)
if (viajero.nombre == "" && check == false) {
cout << "Nombre Viajero: ";
cin >> nombre;
viajero.nombre = nombre;
// check = true; // If you leave this line in, only the first name will get read!
}
}
相关文章:
- 在全局变量中保存类的实例以重新创建类(创建"backup")
- 当vector是tje全局变量时,c++中vector的内存管理
- std::threads可以从Windows DLL中的全局变量创建/销毁吗?
- 内联函数中具有内部链接的全局变量
- 如何在信号处理程序和普通函数中对全局变量进行互斥读写操作
- 全局变量 多读取器 一个写入器多线程安全?
- 如果全局变量默认是外部变量,为什么要添加"extern"关键字?
- 不同作用域中的静态变量和全局变量
- C++ 在编译时具有函数计算全局变量
- 修改程序的入口点时未调用全局变量的构造函数
- 使用 std::ios_base::Init 正确初始化全局变量
- 为什么我的全局变量似乎没有变化?
- C ++程序如何返回我的数组或写入全局变量
- 为什么我的数组值与此处的全局变量不匹配?
- QT C++中对全局变量的未定义引用
- 跨多个类的全局变量而不会出现重定义错误?
- 赋予全局变量而不是局部变量优先级的函数 - (异常行为)
- C++线程不检测全局变量更改
- 在 elf 文件中查找全局变量的位置
- 在C++中使用全局变量进行练习