在C++中访问结构的变量?
Accessing structure's variable in C++?
struct app
{ int id;
char name[20];
char developer[20];
char type[20];
int date_uploaded [3];
};
.
.
.
void search(app a[2])
{
int choice;
char t_check[20];
Dhome();
cout<<"nnSelect the way you want to search for an app"
<<"n(1) To search by app name"
<<"n(2) To search by developer name"
<<"n(3) To search by type"
<<"n(4) To return to previous menun";
cin>>choice;
cin.ignore();
switch(choice)
{
case 1:
Dhome();
cout<<"nnEnter the app's name: ";
search_specific(a,"name");
//Similar cases for passing developer and type
}
}
void search_specific(app a[2], char choice[10])
{ int i, flag=0;
char t_check[20], s_type[5];
gets(t_check);
for(i=0; i<2; i++)
{
if(strcmp(t_check, a[i].choice)==0)
{
flag=1;
break;
}
}
if(flag==1)
{
cout<<"nThe app was found and its details are as below"
<<"nApp ID: "<<a[i].id
<<"nApp Name: "<<a[i].name
<<"nDeveloper Name: "<<a[i].developer
<<"nType: "<<a[i].type
<<"nDate Uploaded: "<<a[i].date_uploaded[0]<<"/"<<a[i].date_uploaded[1]<<"/<<a[i].date_uploaded[2];
cout<<"nnPress enter to return to the previous menu";
getch();
return;
}
if(flag==0)
{
cout<<"nThe app was not found";
cout<<"nnPress enter to return to the previous menu";
getch();
return;
}
}
现在的问题是我不能使用 a[i].choice,因为编译器试图在结构应用程序中找到"选择"。我希望它引用其值,即名称、开发人员或类型。我怎样才能做到这一点?
您必须制定一个 switch
语句,读取类型为 app
的值的所需成员,如下所示。
int choice;
// read choice from somewhere
switch(choice)
{
case 0:
// do something with a[i].id
break;
case 1:
// do something with a[i].name
break;
default;
break;
}
无法按索引访问结构的成员。
C++ 语言不提供可以在运行时反映的一流属性,就像 JavaScript 那样。所以你的问题没有一行的答案。也许最接近您要找的东西的是 std::map
.但是,如果您使用的是像 app
这样的结构,则必须编写自己的代码来从对象中获取每个字段,如 Codor 的示例所示。
相关文章:
- 从结构寻址时,MMAP变量的行为很奇怪
- 访问在 C++ 结构中声明的枚举变量
- 我可以在 C++ 中将数据成员/变量从其定义之外添加到结构中吗?
- 如何为 c++ 的不同变量类型的结构元素创建动态数组?
- 为什么未命名的结构内联变量在每个翻译单元中没有相同的地址?
- 在类构造函数中使用结构变量
- 在 c++ 中将变量作为结构构造函数中的引用传递
- 在类构造函数中定义结构变量的参数
- 为什么我们再次从结构对象创建结构变量?
- 从另一个 cpp 文件更改结构内、映射键内的变量
- 模板化结构中的零大小成员变量
- C++ 结构中的可选变量(变量结构)
- 对其中一个变量的多变量结构进行排序
- 指向非指针变量结构的指针。这些变量在哪里,堆还是堆栈?
- 是好是坏:为了避免使用全局变量/结构体的属性/大量参数而使用巨型结构体
- Cpp变量/结构用于存储128位数据
- 第一私有变量结构中允许的OpenMP调用和指令
- VS2008传递变量-结构与结构组件-优点/缺点
- 在c++类成员函数中使用c库变量/结构成员
- 如何不迷失在执行'<'对于多变量结构