2012-04-12 133 views
2

让我们假设有:类 - 获取函数 - 返回多个值

Class Foo{ 
    int x,y; 

    int setFoo(); 
} 

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

所有我想要实现的是形成我get函数返回多个值。我怎样才能做到这一点?

+0

'std :: pair ' – 2012-04-12 20:58:47

回答

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; } 
}; 
+0

如果我想要做一个'get function',它应该返回我从我的类对象的值是否有一个聪明的方法呢? – 2012-04-12 19:59:17

+0

@BogdanMaier是的,看到编辑答案。 – 2012-04-12 20:01:33

6

你可以参考参数。

void Foo::setFoo(int &x, int &y){ 
    x = 1; y =27 ; 
} 
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); 
1

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

例如:

struct Point { int x; int y; }; 

Class Foo{ 
    Point pt; 

    Point setFoo(); 
}; 

Point Foo::setFoo(){ 
    return pt; 
} 
2

在C你真的不能返回多个值++。但是你可以参考

3

您不能返回多个对象本身修改多个值,但你可以做的是请使用std::pair<utility>std::tuple<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; 
}