1

I have the following code :

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

I want to use toInt function and transfer as a second argument ,argument of type num num n; toInt("2",n); This causes compilation error.

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

I tried to use a cast : toInt("2",(num)n); But it is still problematic How can I solve the issue?

4
  • What is the compiler error? We can't help you if you don't tell us. Commented Nov 24, 2012 at 22:20
  • It's still fairly vague but it's probably because you need a cast. Commented Nov 24, 2012 at 22:24
  • I meant inside the body of the function where the parameter is being used. Except you didn't post your function body so how could I know? Commented Nov 24, 2012 at 22:30
  • -1: The function name is misleading. It should return int, and the matching to enum should be done outside / in other (properly named) function. Commented Nov 24, 2012 at 22:45

2 Answers 2

1

A value of type num isn't an int, so it has to be converted to a temporary int before it is passed to the function. Tempories cannot be bound to a non-const reference.


If you want to convert via an int, you will have to convert in two steps:

int temp;
toInt("2", temp);
num n = static_cast<num>(temp);
Sign up to request clarification or add additional context in comments.

Comments

1

I'd suggested, you add a new enum type for signaing invalid enum e.g:

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

and change the signature to num instead of 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;
}

regards

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.