繁体   English   中英

在C ++中返回多个值和默认参数

[英]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通过引用传递,因此对它们的更改可以直接反映回去。

您可以通过引用传递此信息。

通过这样做,您正在制作一种指向内存位置的方法。 更改该内存位置后,您的值也会更改。

链接http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8a.doc%2Flanguage%2Fref%2Fcplr233.htm

您不能以这种方式这样做。 但是,您可以使用不同数量的参数重载该函数,并返回带有结果的std::vectorstd::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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM