【发布时间】:2014-07-16 22:26:20
【问题描述】:
我有以下使用结构的示例(简化):
#include <iostream>
#include <algorithm>
#include <time.h>
using namespace std;
struct s_str
{
int a=1,b=2,c=3;
};
int main(void)
{
s_str str;
int sel;
srand(time(NULL)); //initialize random seed
sel = rand() % (3); //generate a random number between 0 and 2
cout << "sel: " << sel << endl;
cout << "str: " << str.??? << endl;//I was wondering to output a, b or c
return 0; //depending whether sel=0,1,2respectively.
}
当结构体“str”被定义后,我们可以使用操作符“.”来访问每个元素。后跟元素的名称。例如“str.c”会给我们数字 3。
但是在这个例子中,我们不知道编程时要输出的“str”元素,因为它是由 sel 随机选择的。
我不知道如何输出“str.???”从 sel 编号,即如果 sel=0,则 str.a,如果 sel=1,则 str.b,如果 sel=3,则 str.c。
我尝试了类似“str.[sel]”的方法,但没有成功。你能帮助我吗?
PD:我不想太麻烦,但是如何解决同样的问题,但现在假设 a、b 和 c 具有不同的变量类型。例如:
int a=1,b=2;
string c="hola";
我尝试用两个运算符来做,但由于它们被重载,它没有编译。
【问题讨论】:
-
如果没有将索引映射到成员,则不可移植。
-
谢谢大家的回答!