How do you pass an enum by reference?
I have an enum with four keys I'm taking as input for an interface program and I'd like to pass the enum by value to the interface function, which has become quite long. The enum is like this:
enum MYKEYS {
W, S, O, L
};
There's also a boolean array 开发者_C百科that I have to pass by reference, which is also a little tricky.
bool key[4] = { false, false, false, false };
Does anyone know the proper syntax to pass both of these as reference in a function, similar to:
function(int & anintreference);
You can't pass the enum
itself as a parameter of your function! The enum
defines a new type, and you can create a variable of this type, that may take one of the value defined by the enum
:
MYKEYS k = W;
Only then you could pass k
by reference to some function:
function foo(MYKEYS& k_);
Regarding your second question, since you should think of the array as a pointer to a series of bool
:
function bar(bool* key, int length);
For the bool array, just take a bool* keys
pointer. That works because arrays decay to pointers when passed to a function:
bool key[4] = {false, false, false, false};
void FuncThatTakesABoolArray(bool* keys){
bool key1 = keys[0];
// etc...
}
For the enum, Greg already answered that.
With enum you are defining a new type in your program. This type behaves the same way that any type. Then the pass by value is:
void myFunction( MYKEYS key );
And the pass by reference:
void myFunction( MyKEYS& key );
If key will not be modified, better will be declare const reference:
void myFunction( const MyKEYS& key );
Relative to a vector:
Vectors always are pass by reference in C++, and you don't need a pointer to do this. The syntax is a bit different that normal types.
void myFunction( bool keyVector [ ] );
Pass by reference is normally better than a pointer because someone can pass a NULL pointer to your function and break the program if you don't check the pointer previously.
In a matrix, ( a vector of vectors ) you must specify all dimensions except the first:
bool keysOfKeys[4][3];
void myFunction( bool vector [ ] [ 3 ] );
There is a better form to do this without a vector of bools.
You can use the operator & ( bitwise and ) and ( | bitwise or ) and use each bit as a bool. Remind that a enum behaves as a int.
For example, if the user has pressed the keys W and S.
enum MYKEYS
{
W = 1<<0, // ..0001 ( binary )
S = 1<<1, // ..0010 ( binary )
O = 1<<2, // ..0100 ( binary )
L = 1<<3 // ..1000 ( binary )
};
MYKEYS k;
k = W | S; // W and S pressed: ..0011 ( binary )
void myFunction( eKey key )
{
// ..0011 & ..0001 -> ..0001
if ( ( key & W ) == W ); // key W pressed
// ..0011 & ..0010 -> ..0010
if( ( key & S ) == S ); // key S pressed
}
Just use this way in your program:
foo(*new MYKEYS(MYKEYS::W));
And foo decleration/definition is like that:
void foo(MYKEYS &newMYKEYS){
//
}
精彩评论