我正在尝试查看是否可以像在 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
按值(value):
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)本身并使用您已经拥有的单 setter/getter 。
关于c++ - 在 C++ 的方法返回中组合多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31857546/