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

Returning multiple values and default parameters in C++

本文关键字:默认 参数 c++ 返回      更新时间:2023-10-16

我正试图使一个函数接受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);
}

任何函数总是只返回一个值。不能直接返回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);
}

你也可以使用boost::optional,如果你只想返回x,如果只有一个参数传递。

顺便说一句。tuple在c++ 11中也可用。