开发者

c++ default parameters [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Nonstatic member as a default argum开发者_如何学JAVAent of a nonstatic member function

Ok. So I'm having problems understanding how to accomplish a seemingly simple task... Here is what I want to accomplish:

#include <iostream>

using namespace std;

class A{
private:
    int _x;
public:
    A(int x){
        _x = x;
    }

    void test(int x=_x){
        cout << x << endl;
    }
};

int main(){
    A a(3);
    a.test();
}

The compiler complains about the int x=_x part saying error: invalid use of non-static data member A::_x

So how do I use a default parameter like this?

Thanks.


You can't do that.

You can however have an overload for test that takes no parameters.

void test(){
    test(_x);
}


You cannot do that. However if you declare _x as static data member as:

static int _x; //_x is static data member now!

Then you can do that, i.e you can use _x as default value for parameters in your member functions.

A nice example from the C++ Standard itself. Quoting from section §8.3.6/9 :

Similarly, a nonstatic member shall not be used in a default argument expression, even if it is not evaluated, unless it appears as the id-expression of a class member access expression (5.2.5) or unless it is used to form a pointer to member (5.3.1). [Example: the declaration of X::mem1() in the following example is ill-formed because no object is supplied for the nonstatic member X::a used as an initializer.

int b;
class X {
   int a;
   int mem1(int i = a); // error: nonstatic member a used as default argument
   int mem2(int i = b); // OK; use X::b
   static int b;
};

The declaration of X::mem2() is meaningful, however, since no object is needed to access the static member X::b.

Hope it helps.


Does your function have a sentinel (-1)?

void test(int x=-1)
{
    if(x == -1)
        x = _x;

    //Rest of code
}

You could also use:

void test(int x, bool bUseLocal=false)
{
    if(bUseLocal)
        x = _x;

    //Rest of code
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜