简体   繁体   中英

Set default for class member function's struct input

I have the following code, and would like to give default value for param3. I have tried various attempts, and compiler's error msg seems to be saying in class non-int initialization is not allowed. Is this a bad practice and why? What's a better approach from a OO perspective?
thanks

struct MyStruct 
{ 
    int a; 
    int b;
};
class myClass {
    public:
        void init(int param1 = 0, int param2 = 0, MyStruct param3);
}

You could add a constructor and a default constructor MyStruct and make a constant default value like this:

struct MyStruct { 
    int a; 
    int b;
    MyStruct(int x, int y):a(x), b(y) {} // Constrctor.
    MyStruct():a(0), b(0) {}             // Default constrctor.
};

const MyStruct default_(3, 4);           // for instance here by default a == 3 and b == 4

class myClass {
    public:
        void init(int param1 = 0, int param2 = 0, MyStruct param3 = default_);
};

以下将起作用(至少在C ++ 11中有效):

void init(int param1 = 0, int param2 = 0, MyStruct param3 = MyStruct{ 2, 3 });

Probably the simplest and clearest way to solve a problem like this would be to do something like this:

class myClass {
  public:
    void init(int p1 = 0, int p2 = 0)
    {
       MyStruct s; //initialize this to whatever default values
       init(p1, p2, s);
    }
    void init(int p1, int p2, MyStruct p3);
}

This will work in C++0x.

struct MyStruct 
{ 
    int a; 
    int b;
};

function foo(int a, structure s = structure{10,20}) 
{
    //Code
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM