[英]Returning multiple values and default parameters in C++
我正在尝试使一个函数接受1或3个参数,并返回1或3个值(基于传递的参数)。
如果传递了1个参数,则该函数对其他2个参数使用默认值。 如果传递了3个参数,则它将使用这些值。
bool foo( bool x, int &y = 0, int &z = 0) {
x = true; y = y + 1; z = z + 2;
return x;
}
这在C ++中可能吗?还是我对Java函数感到困惑?
您可以使用以下两个功能来做到这一点:
bool foo( bool x, int &y, int &z) {
x = true; // this isn't really what it does, is it?
y = y + 1; z = z + 2;
return x;
}
bool foo(bool x)
{
int a = 0, b = 0;
return foo(x,a,b);
}
任何函数始终仅返回1值 。 无法直接返回2个或多个值。
当您通过引用传递参数时,会间接发生。 由于两个参数&y
和&z
通过引用传递,因此对它们的更改可以直接反映回去。
您可以通过引用传递此信息。
通过这样做,您正在制作一种指向内存位置的方法。 更改该内存位置后,您的值也会更改。
您不能以这种方式这样做。 但是,您可以使用不同数量的参数重载该函数,并返回带有结果的std::vector
或std::list
。
编辑 :
更复杂的是,您可以使用元组:
typedef boost::tuple<bool,int,int> my_data_t;
my_data_t my_tuple(true, 1, 0);
然后,您可以这样定义函数:
bool foo( my_data_t & t)
{
t.get<0>() = true;
int& y = t.get<1>();
y = y+1;
int& z = t.get<2>();
z = z+2;
return t.get<0>();
}
并这样称呼:
bool result = foo ( my_tuple );
然后,在函数之外,您将看到my_tuple.get<1>()
(与y
对应)为2(1 + 1)。
我不确定您要做什么,但是您可以使用boost::tuple
返回多个不同类型的值。
boost::tuple<bool, int, int> foo( bool x, int y = 0, int z = 0) {
x = true; y = y + 1; z = z + 2;
return boost::make_tuple(x, y, z);
}
int main() {
boost::tuple<bool, int, int> result = foo(x, 1, 2);
std::cout << boost::get<0>(result) << boost::get<1>(result) << boost::get<2>(result);
}
如果只想传递x,并且只传递了1个参数,也可以使用boost::optional
。
顺便说一句。 tuple
在C ++ 11中也可用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.