C ++函数能返回多个值吗? [英] Can a C++ function return more than one value?

查看:522
本文介绍了C ++函数能返回多个值吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

函数是否可以返回多个值?

我想从c ++函数返回3个变量,但因为一个函数只能有一个正在运行的返回值,如何返回3个值。尝试使用return(5,4);但这是一个语法错误。

I want to return 3 variables from a c++ function but as one function can have only one running return value how I can return 3 values. tried using return(5,4); but this is an syntax error.

推荐答案

C ++函数只能返回一个值。但是,您可以通过将它们包装到类或结构中来返回多个值。

A C++ function can return only one value. However, you can return multiple values by wrapping them in a class or struct.

struct Foo
{
     int value1;
     int value2;
};

Foo SomeFunction()
{
    Foo result = { 5, 4 };
    return result;
}

也可以使用 std :: tuple ,如果这是您的编译器可用。

Or you could use std::tuple, if that is available with your compiler.

#include <tuple>

std::tuple<int, int, int> SomeFunction()
{
    return std::make_tuple(5, 4, 3);
}

如果您事先不知道要输入多少个值返回, std :: vector 或类似的容器是你最好的选择。

If you don't know in advance how many values you're going to return, a std::vector or a similar container is your best bet.

通过具有指针或引用参数到你的函数,并在你的函数中修改它们,但我认为返回一个复合类型通常是一个更清洁的方法。

You can also return multiple values by having pointer or reference arguments to your function and modifying them in your function, but I think returning a compound type is generally speaking a "cleaner" approach.

这篇关于C ++函数能返回多个值吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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