C++:类内函数用于多个变量值
有点菜鸟问题。在一个名为“cell”的类中,我有一个枚举“Example”说
typedef enum Example
{
E1=0,
E2,
E3,
E4
};
Example inputValueE;
此外,我在类内有一个函数,如下
void evolveE(Example type_);
在类外,我尝试为几种类型定义函数,如下所示
void cell::evolveE(Example type_ = E1){****some stuff****;};
void cell::evolveE(Example type_ = E2){****some diff stuff****;}; ***etc***
我已经玩过这些了,但是没有运气。问题是我不允许重新定义相同的函数。我打算使用 switch-case type 命令,该命令始终是备份,尽管我很确定有一种更优雅的方法来执行此操作,
非常感谢任何帮助。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
重载函数时(在类中提供多个同名函数),您需要为每个函数提供一组不同的参数类型,如下所示:
请注意,这里,一个函数接受一个
Example
类型的参数,另一个采用OtherExample
类型的参数。尽管您在尝试重载的函数中提供了不同的默认值,但这两个函数都采用相同的参数类型,因此编译器无法区分它们之间的区别。您可以使用开关,但我更喜欢 if/else,因为它不太容易出现错误。
如果
Example
枚举确实决定了类的类型,那么您可以使用多态性。这是 OOP 的一个非常优雅的特性。然后你可以有这样的东西: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:
Notice that here, one function takes an argument of type
Example
and the other takes an argument of typeOtherExample
. 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:该语法设置默认参数。它与调用者传递的实际参数不匹配。使用
switch
/case
。如果您想要更花哨,您还可以使用函数指针数组(或映射)。
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.
对于这个语句:
有两点:
evolveE
的参数设置一个默认值,不使其采用
enum
类型只能使用不同类型和数量的参数进行重载
解决方案之一:
您可以选择使用使每个值成为独立类型:
For this statement:
Two points:
evolveE
's parameter andnot making it to take a type of
enum
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: