在C++中使用全局变量进行练习

Exercise with global variables in C++

本文关键字:练习 全局变量 C++      更新时间:2023-10-16

我在练习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!
}
}