假设我们有:
Class Foo{
int x,y;
int setFoo();
}
int Foo::setFoo(){
return x,y;
}
我想要实现的只是从我的 get 函数中返回多个值。我怎样才能做到这一点?
假设我们有:
Class Foo{
int x,y;
int setFoo();
}
int Foo::setFoo(){
return x,y;
}
我想要实现的只是从我的 get 函数中返回多个值。我怎样才能做到这一点?
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; }
};
您可以有参考参数。
void Foo::setFoo(int &x, int &y){
x = 1; y =27 ;
}
您本身不能返回多个对象,但您可以使用std::pair
from<utility>
或std::tuple
from <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;
}
您不能真正在 C++ 中返回多个值。但是可以通过引用修改多个值
您不能返回超过 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);
C++ 不允许您返回多个值。您可以返回包含多个值的类型。但是您只能从 C++ 函数返回一种类型。
例如:
struct Point { int x; int y; };
Class Foo{
Point pt;
Point setFoo();
};
Point Foo::setFoo(){
return pt;
}
您可以使用std::pair
两个返回的变量和std::tuple
(仅限 C++11)更多的变量。