a bit of a noob problem. Inside a class called 'cell', I have an enum 'Example' say
typedef enum Example
{
E1=0,
E2,
E3,
E4
};
Example inputValueE;
Also I have a function inside class as follows
void evolveE(Example type_);
Outside the class, I attempt to define the function for several types as follows
开发者_运维技巧void cell::evolveE(Example type_ = E1){****some stuff****;};
void cell::evolveE(Example type_ = E2){****some diff stuff****;}; ***etc***
I've played around with these a bit but with no luck. The problem is i'm not allowed to redefine the same function. I was going to use the switch-case type command which is always backup although i'm pretty sure there is a more elegant way to do this
Any help is much appreciated.
That syntax sets a default argument. It does not match the actual parameter passed by the caller. Use switch
/case
.
If you want to be fancy, you could also use an array (or map) of function pointers.
For this statement:
void cell::evolveE(Example type_ = E1);
Two points:
- Here you are setting a default value for
evolveE
's parameter and not making it to take a type ofenum
- You cannot overload functions based on values of any kind; function can be overloaded only with different types and number of parameters
One of the solution:
You can choose to use make every value an independent type:
enum E1 {};
enum E2 {};
enum E3 {};
When overloading a function (providing more than one function with the same name in a class), you need to provide a different set of argument types to each function like this:
void cell::evolveE(Example type_){****some stuff****;}
void cell::evolveE(OtherExample size_){****some diff stuff****;}
Notice that here, one function takes an argument of type Example
and the other takes an argument of type OtherExample
. Although you provide different default values in the function you are trying to overload, both functions take the same argument type and so the compiler has no way of telling the difference between them.
You could use a switch although I would prefer an if/else because it is less prone to bugs.
If the Example
enum is really determining the type of your class you could use polymorphism. It is a very elegant feature of OOP. Then you could have something like this:
class cell
{
...
virtual void evolveE() = 0;
};
class E1cell : public cell
{
...
void evolveE()
{
// some stuff
}
};
class E2cell : public cell
{
...
void evolveE()
{
// some diff stuff
}
};
精彩评论