枚举引用参数转移而不是int引用参数

时间:2012-11-24 22:19:54

标签: c++ reference enums

我有以下代码:

typedef enum {Z,O,T} num;
bool toInt (str s,int& n);//<-if convert is possible converts s to integer ,puts the result in n and returns true,else returns false

我想使用toInt函数并作为第二个参数传递,类型为num的参数 数字; toInt( “2”,N); 这会导致编译错误。

cannot convert parameter 2 from 'num' to 'int &'

我尝试使用演员:toInt("2",(num)n);但它仍然存在问题 我该如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

类型num的值不是int,因此在将其传递给函数之前必须将其转换为临时int。 Tempories不能绑定到非const引用。


如果要通过int转换,则必须分两步进行转换:

int temp;
toInt("2", temp);
num n = static_cast<num>(temp);

答案 1 :(得分:1)

我建议你添加一个新的枚举类型来表示无效的枚举,例如:

enum num {Z,O,T,Invalid=4711} ;//no need to use typedef in C++

并将签名更改为num而不是int:

bool toInt (str s, num& n)
{
 if ( s=="Z" ) n=Z; 
 else if ( s=="O" ) n=O;
 else if ( s=="T" ) n=T;
 else { n=Invalid; return false; }
 return true;
}

问候

相关问题