c++中在方法返回中组合多个值

Combining multiple values in method return in C++

本文关键字:组合 返回 方法 c++      更新时间:2023-10-16

我想看看是否有可能以相同的方式组合多个get值,您可以在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;}

当然,按值返回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);
}

虽然你可能不想写这种东西。只需传递类本身,并使用您已经拥有的单个getter。

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

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

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

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