![](/img/trans.png)
[英]Unexpected compile error in C++: passing default value to function parameter
[英]Passing default parameter to function C++
我想使用默认参数或由我给定的函数来调用函数,但是默认参数是指定的类私有变量,此处为简化示例:
Class::Something
{
public:
void setI(int i);
private:
void func(int i = this->i_default, j=this, k=this->k_default, l=this->l_default);
int i_default; // May be different for different instances.
int k_default; // May be different for different instances.
int l_default; // May be different for different instances.
}
因此,当我调用func()时,它将采用默认的i_variable;当我调用func(4)时,它将采用4个参数,而不会更改i_default值。 我知道我做错了事,因为我得到错误:
Error 1 error C2355: 'this' : can only be referenced inside non-static member functions or non-static data member initializer
有什么方法可以实现这种行为?
有什么方法可以实现这种行为?
使用函数重载(感谢@PiotrSkotnicki):
void func(int i);
void func() { func(i_default); }
该标准对此很明确。 您显然不能在默认参数中使用this
。 您似乎注定要使用重载来实现此结果:
void func(int i);
void func() { func(i_default); }
如果要保留功能,可以使用哨兵,该哨兵可以让func
决定是否使用默认值。 最简单的形式:
void func(int* pi = NULL) {
int i = pi ? *pi : i_default;
// rest of the function
}
可以扩展此方法以使用帮助程序类:
#include <cstdio>
template <typename C, typename T>
class Defaltable {
T val;
T C::* ptr;
public:
Defaltable(int C::* p) {
ptr = p;
val = 0;
}
Defaltable(T x) {
val = x;
ptr = NULL;
}
T fetch(C* p) {
return ptr ? p->*ptr : val;
}
};
class Foo {
int i_default;
public:
Foo(int dflt) {
i_default = dflt;
}
int func(Defaltable<Foo, int> x = &Foo::i_default) {
return x.fetch(this);
}
};
int main()
{
Foo c(42);
printf("%d\n", c.func(1));
printf("%d\n", c.func());
}
您可以将i_default声明为const static (感谢@TartanLama )。
const static int i_default=1;
这是工作程序 。
您还可以使用函数重载 。 但这比函数重载使用更少的代码!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.