在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);
}
任何函数总是只返回一个值。不能直接返回2个或更多的值。
间接地发生在通过引用传递参数时。由于&y
和&z
这两个参数是通过引用传递的,所以对它们的改变可以直接反映出来。
可以通过传递引用来实现。
通过这样做,您创建了一个指向内存位置的方法。当内存位置改变时,您的值也随之改变。
链接http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8a.doc%2Flanguage%2Fref%2Fcplr233.htm
你不能这样做。但是,您可以用不同数量的参数重载该函数,并返回结果的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);
}
你也可以使用boost::optional
,如果你只想返回x,如果只有一个参数传递。
顺便说一句。tuple
在c++ 11中也可用。
相关文章:
- 如何使用默认参数等选择模板专业化
- 当函数模板参数是具有默认参数的类模板时,函数模板参数的推导如何执行
- 何时提供默认参数作为模板参数
- 将const引用参数初始化为默认参数会导致悬空引用吗
- 如何修复带有 clang 的参数'args'缺少默认参数的问题?
- 函数不接受 X 参数,函数使用默认参数
- initializer_list具有默认参数的构造函数
- C++ 带有默认参数的结构,可选择在构造函数中更改
- 为什么C++构造函数在继承中需要默认参数?
- 必须非常量别名参数及其默认参数常量
- C++ 默认参数使用其他参数
- 组合函数参数包和默认参数
- 如何定义 Vector2f 的默认参数?[SFML]
- 有条件地将默认参数传递给函数(使用"?"运算符)
- 使用具有默认参数的函数模板进行 decltype 会使结果混乱(一个有趣的问题或 gcc 的错误)
- 如何设置默认参数以防用户不输入另一个参数
- 结构 c++ 中的默认参数
- 构造函数委托与默认参数
- 默认参数和函数指针作为函数参数C++
- 如何在继承层次结构中调用具有默认参数的构造函数?