Default value for struct parameter

橙三吉。 提交于 2019-12-23 11:58:03

问题


Let's say I have the following struct:

struct myStruct
{
 int x;
 int y;
 int z;
 int w;
};

I want to initialize this struct to a default value when calling the following function. If it helps I'm looking for a simple zero initialization.

void myFunc(myStruct param={0,0,0,0})
{
 ...
}

This code however gives me compile error. I've tried VS2003 and VS2008.

NOTE: I have looked at other answers mentioning the use of constructor. However I want the user to see what values I'm using for initialization.


回答1:


Adding default constructor in to your myStruct will solves your problem.

struct myStruct {
   myStruct(): x(0),y(0), z(0), w(0) { }   // default Constructor
   int x, y, z, w;
};

Function declaration:

void myFunc(myStruct param = myStruct());



回答2:


For modern C++ compilers which fully implement value-initilization it is enough to have the following value-initialized default value to zero-initiliaze data members of the myStruct:

myFunc(myStruct param=myStruct())

For other compilers you should to use something like this:

myStruct zeroInitilizer() {
   static myStruct zeroInitilized;
   return zeroInitilized;
}
myFunc(myStruct param=zeroInitilizer())

To avoid compiler specifics conside to use http://www.boost.org/doc/libs/1_53_0/libs/utility/value_init.htm



来源:https://stackoverflow.com/questions/15307954/default-value-for-struct-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!