2

假设我们有:

Class Foo{
    int x,y;

    int setFoo();
}

int Foo::setFoo(){
    return x,y;
}

我想要实现的只是从我的 get 函数中返回多个值。我怎样才能做到这一点?

4

7 回答 7

10

C++ 不支持多个返回值。

您可以通过参数返回或创建辅助结构:

class Foo{
    int x,y;

    void setFoo(int& retX, int& retY);
};

void Foo::setFoo(int& retX, int& retY){
    retX = x;
    retY = y;
}

或者

struct MyPair
{
   int x;
   int y;
};

class Foo{
    int x,y;

    MyPair setFoo();
};

MyPair Foo::setFoo(){
    MyPair ret;
    ret.x = x;
    ret.y = y;
    return ret;
}

另外,不应该调用您的方法getFoo吗?只是在说...

编辑:

你可能想要的:

class Foo{
    int x,y;
    int getX() { return x; }
    int getY() { return y; }
};
于 2012-04-12T19:54:25.677 回答
6

您可以有参考参数。

void Foo::setFoo(int &x, int &y){
    x = 1; y =27 ;
}
于 2012-04-12T19:54:38.347 回答
3

您本身不能返回多个对象,但您可以使用std::pairfrom<utility>std::tuplefrom <tuple>(后者仅在最新的 C++ 标准中可用)将多个值打包在一起并将它们作为一个对象返回。

#include <utility>
#include <iostream>

class Foo
{
  public:
    std::pair<int, int> get() const {
        return std::make_pair(x, y);
    }

  private:
    int x, y;
};

int main()
{
    Foo foo;
    std::pair<int, int> values = foo.get();

    std::cout << "x = " << values.first << std::endl;
    std::cout << "y = " << values.second << std::endl;

    return 0;
}
于 2012-04-12T19:57:48.747 回答
2

您不能真正在 C++ 中返回多个值。但是可以通过引用修改多个值

于 2012-04-12T19:57:41.390 回答
1

您不能返回超过 1 个变量。但是您可以通过引用传递,并修改该变量。

// And you pass them by reference
// What you do in the function, the changes will be stored
// When the function return, your x and y will be updated with w/e you do.
void myFuncition(int &x, int &y)
{
    // Make changes to x and y.
    x = 30;
    y = 50;
}

// So make some variable, they can be anything (including class objects)
int x, y;
myFuncition(x, y);
// Now your x and y is 30, and 50 respectively when the function return
cout << x << " " << y << endl;

编辑:回答你关于如何获取的问题:你传递一些变量,而不是只返回 1 个变量,所以你的函数可以修改它们,(当它们返回时),你会得到它们。

// My gen function, it will "return x, y and z. You use it by giving it 3 
// variable and you modify them, and you will "get" your values.
void myGetFunction(int &x, int &y, int &z)
{
    x = 20;
    y = 30;
    z = 40;
}

int a, b, c;
// You will "get" your 3 value at the same time when they return.
myGetFunction(a, b, c);
于 2012-04-12T19:54:49.470 回答
1

C++ 不允许您返回多个值。您可以返回包含多个值的类型。但是您只能从 C++ 函数返回一种类型。

例如:

struct Point { int x; int y; };

Class Foo{
    Point pt;

    Point setFoo();
};

Point Foo::setFoo(){
    return pt;
}
于 2012-04-12T19:56:08.437 回答
1

您可以使用std::pair两个返回的变量和std::tuple(仅限 C++11)更多的变量。

于 2012-04-12T20:01:55.647 回答