[英]Set default for class member function's struct input
I have the following code, and would like to give default value for param3. 我有以下代码,并希望为param3提供默认值。 I have tried various attempts, and compiler's error msg seems to be saying in class non-int initialization is not allowed.
我尝试了各种尝试,并且编译器的错误msg似乎在类中说不允许进行非整数初始化。 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: 您可以添加一个构造函数和一个默认构造函数
MyStruct
并像下面这样创建一个恒定的默认值:
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. 这将在C ++ 0x中工作。
struct MyStruct
{
int a;
int b;
};
function foo(int a, structure s = structure{10,20})
{
//Code
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.