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

标签 c++ getter-setter

我正在尝试查看是否可以像在 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/

相关文章:

c++ - `constexpr std::initializer_list` 可以在编译时使用但不能用于 ODR 吗?

c++ - Qt 自定义控件大小

java - 循环使用 get 和 set 吗?

swift - 什么时候调用计算属性的修改方法,它做什么?

c++ - 使用 g4 压缩压缩输出 tiff

c++ - 派生模板类访问基类成员数据

c++ - newComputePipelineStateWithFunction 失败

objective-c - 为什么这个 UIView 在某些情况下没有被添加为 subview ,但在其他情况下却可以?

C++:在显示一些数据时避免 setter/getter

javascript - ES6 类 setter 不被识别为函数