在 C++ 中组合方法 return 中的多个值

Combining multiple values in method return in C++

我正在尝试查看是否可以像在 C++ 中使用 setter 一样组合多个获取值。我正在使用一本书中的示例,该示例将每个 getter 放在单独的行上。

我为 setter 使用的示例如下:

void setValues(int, int, string);

void myClass::setValues(int yrs, int lbs, string clr)
{
    this -> age = yrs;
    this -> weight = lbs;
    this -> color = clr;
}

是否可以为多个 getter 值编写单行代码,例如这些?

int getAge(){return age;};
int getWeight(){return weight;}
string getColor(){return color;}

当然,return std::tuple 按值:

std::tuple<int, int, string> getAllTheValues() const
{
    return std::make_tuple(age, weight, color);
}

或引用:

std::tuple<int const&, int const&, string const&> getAllTheValues() const
{
    return std::tie(age, weight, color);
}

尽管您可能不想真正编写此类内容。只需传递 class 本身并使用您已经拥有的单吸气剂。

您可以通过引用传递而不是返回值,例如:

void getValues(int & yrs, int & lbs, string & clr) const
{
   yrs = this->age;
   lbs = this->weight;
   clr = this->color;
}

您可以像这样编写一个获取引用作为输入的函数:

void getAllTheValues(int& age, int& weight, std::string& color) {
  age = this->age;
  weight = this->weight;
  color = this->color;
}

并像那样使用它

int age, weight;
string color;

myClass object();
object.getAllTheValues(age, weight, color);

这是一个还没有人提到的解决方案:

struct values { int age; int weight; string color; };

values getValues() const
{
    return { this->age, this->weight, this->color };
}