C ++中的结构引用的默认参数 [英] Default argument for structure reference in C++

查看:114
本文介绍了C ++中的结构引用的默认参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想给一个函数参数一个默认值,它是对一个结构的引用。

第一个解决方案: p>

如果它是一个struct的引用,那么你必须使它 const 引用, / p>

  struct A 
{
// etc
A(int,int);
};

void f(int a,const A& = A(10,20))// const is necessary
{
// etc
}

这不是很明显的原因:它使参数 const (你可能不想要它),你的struct需要有构造函数(你可能没有它)。



strong>



所以如果你不想让它 const ,或者如果你不想在结构中有一个构造函数,那么你可以这样做:

  struct Point 
{
int x ,y,z;
};

Point g_default_point = {10,20,30};
void g(int a,Point& p = g_default_point)
{
// etc
}

仍然不好。定义全局变量不是一个好主意。






最佳解决方案:定义重载函数



  void g(int a,Point& p)
{
//您的代码
}
void g(int a)//这个函数的行为就像你选择默认值!
{
Point default_value = {10,20,30};
g(a,default_value);
}

现在不需要你做参数 const ,它也不会强制你在你的结构体中有构造函数。


I want to give a default value to a function parameter, which is reference to a structure . What can I give as the default value ?

解决方案

First solution:

If it is a reference to a struct, then you've to make it const reference, and do this:

struct A
{
    //etc
    A(int, int);
};  

void f(int a, const A & = A(10,20) ) //const is necessary
{
    //etc
}

Its not that good for the obvious reasons: it makes the parameter const (you may not want it), and your struct needs to have constructor (you may not have it).

Second solution:

So if you don't want to make it const, or if you don't want to have a constructor in the struct, then you can do this:

struct Point
{
     int x, y, z;
};  

Point g_default_point = {10,20,30};
void g(int a, Point & p = g_default_point )
{
    //etc
}

Still not good. Defining a global variable is not a great idea.


Best solution : define an overload function

void g(int a, Point & p)
{
    //your code
}
void g(int a) //this function would behave as if you opt for default value!
{
     Point default_value = {10,20,30};
     g(a, default_value);
}

Now it doesn't require you to make the parameter const, neither does it force you to have constructor in your struct.

这篇关于C ++中的结构引用的默认参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆