将默认参数传递给函数C ++

时间:2015-10-21 07:31:02

标签: c++ function this default

我想用默认参数调用函数或者由我给出,但是默认参数是指定的类私有变量,简化示例在这里:

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

是否有某种方式来实现这种行为?

3 个答案:

答案 0 :(得分:0)

  

是否有某种方式来实现这种行为?

使用函数重载(感谢@PiotrSkotnicki):

void func(int i);
void func() { func(i_default); }

答案 1 :(得分:0)

标准很明确。您明确地不能在默认参数中使用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());
}

答案 2 :(得分:0)

您可以将i_default声明为 const static (感谢@TartanLama)。

const static int i_default=1;

这是working program

您还可以使用功能重载。但这比使用函数重载使用更少的代码!