[英]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.