开发者

Set default parameter of a function as an array [duplicate]

This question already has answers here: 开发者_开发知识库 Closed 11 years ago.

Possible Duplicate:

Default values for array arguments

How do I give an array as the default parameter to a function? I tried this:

void drawCircle(float radius, GLfloat colour[3]={2.0, 3.0, 4.0}, bool do=true) {
...
}

The part GLfloat colour[3]={2.0, 3.0, 4.0} gives me an error. Is this possible in C++?


In C++, You cannot pass a complete block of memory by value as a parameter to a function, but You are allowed to pass its address.

So NO, you cannot do that atleast in C++03.

You can do this:

GLfloat defaultColor[3] = {2.0, 3.0, 4.0}; 

void drawCircle(float radius, GLfloat colour[3]= defaultColor, bool do=true)
{
}


You cannot pass an array by value, and so you cannot do that.

So the workaround is, overload the function as:

void drawCircle(float radius, GLfloat *colour, bool pleaseDo) 
{
  //...
}
void drawCircle(float radius, GLfloat *colour)
{
  drawCircle(radius, colour, true);
}
void drawCircle(float radius) 
{
   GLfloat colour[3]={2.0, 3.0, 4.0};
   drawCircle(radius, colour, true);
}

drawCircle(a,b,c); //calls first function
drawCircle(a,b);   //calls second function
drawCircle(a);     //calls third function

Second and third function eventually call the first function!

Also note that do is a keyword, so you cannot use it as variable name. I replaced it with pleaseDo :D


You can define your default value as a global variable. Then, use this global variable as default argument to the function.

GLfloat default_colour[3] = {2.0, 3.0, 4.0};

void drawCircle(float radius, GLfloat colour[3] = default_colour, bool doit = true)
{
}

Btw, do is a keyword, you cannot use it as a parameter name.


You can't quite do what you want to do but this solution works on my compiler:

static GLFloat DefaultColour[]={2.0,3.0,4.0}
void drawCircle(float radius, GLfloat colour[]=DefaultColour, bool do=true) {
...
}


I think that the Initializer Lists feature from C++11 can help in your question.

void drawCircle(float radius, std::initializer_list<float> colors = {0.9f, 0.2f, 0.7f}, bool do=true)
{

    if (colors.size() == 3)
    {
        // parse the values...
    }

...
}


// and then...

drawCircle(10.0f);

Unfortunately I'm not sure that this feature is up on your compiler :(

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜