C++ 类-获取函数-返回多个值

C++ 类-获取函数-返回多个值,c++,class,return-value,C++,Class,Return Value,假设我们有: 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&

假设我们有:

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

另外,您的方法不应该被称为
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 ;
}

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


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

struct Point { int x; int y; };

Class Foo{
    Point pt;

    Point setFoo();
};

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

<>你不能在C++中返回多个值。但是,可以通过引用< /p> 修改多个值,但本身不能返回一个以上的对象,但可以使用<代码> STD::配对< >代码> <代码> <代码>或代码> STD::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;
}
#包括
#包括
福班
{
公众:
std::pair get()常量{
返回std::生成_对(x,y);
}
私人:
int x,y;
};
int main()
{
富富,;
std::pair values=foo.get();

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

如果我想执行一个“get函数”,它应该从类对象返回值,有没有一种聪明的方法?
// 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);
struct Point { int x; int y; };

Class Foo{
    Point pt;

    Point setFoo();
};

Point Foo::setFoo(){
    return pt;
}
#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;
}