如何在C ++中将默认参数设置为类对象? [英] How to set default parameter as class object in c++?
问题描述
我想将类对象参数设置为默认值来设置函数。但是当我尝试这样做时,编译失败。
I want to set my function with class object parameter set as default. But when I try to do that it fails in compilation.
class base {
// ...
};
int myfunc(int a, base b = NULL) {
if (NULL = b) {
// DO SOMETHING
} else {
// DO SOMETHING
}
}
在这里,当我尝试编译时它,这给了我一个错误,即默认参数基础b具有int类型
Here when i am trying to compile it, this gives me error that "Default Argument base b have int type"
推荐答案
您在这里有三个明显的选择。
You have three obvious options here.
首先,使用重载,以便呼叫者可以选择是否通过 b
。
First, use overloads so the caller can choose to pass b
or not.
int myfunc(int a) { ... }
int myfunc(int a, base& b) { ... }
这样,您可以使用 b
而不使用指针。请注意,应将 b
用作引用或指针类型,以避免切片对象。
This way you can pass b
without having to use a pointer. Note that you should make b
a reference or pointer type to avoid slicing the object.
第二,如果您不希望有两个单独的实现,请制作 b
指针,可以将其设置为 NULL
。
Secondly, if you don't want 2 separate implementations, make b
a pointer, which can be set to NULL
.
int myfunc(int a, base* b = NULL) { ... }
第三,您可以使用某些方法封装可为空的概念,例如 boost :: optional
。
Third, you could use something to encapsulate the concept of nullable, such as boost::optional
.
int myfunc(int a, boost::optional<base&> b = boost::optional<base&>()) { ... }
这篇关于如何在C ++中将默认参数设置为类对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!