[英]Combining multiple values in method return in C++
I am trying to see if it is possible to combine multiple get values in the same way you can use a setter in C++. 我试图看看是否有可能以与在C ++中使用setter相同的方式组合多个get值。 I am using examples from a book which puts each getter on a separate line.
我正在使用一本书中的示例,该示例将每个getter放在单独的行上。
an example I am using for a setter is as follows: 我用于设置器的示例如下:
void setValues(int, int, string);
void myClass::setValues(int yrs, int lbs, string clr)
{
this -> age = yrs;
this -> weight = lbs;
this -> color = clr;
}
Is it possible to do write single line of code for multiple getter values such as these? 是否可以为多个这样的getter值编写一行代码?
int getAge(){return age;};
int getWeight(){return weight;}
string getColor(){return color;}
Sure, return a std::tuple
by value: 当然,按值返回一个
std::tuple
:
std::tuple<int, int, string> getAllTheValues() const
{
return std::make_tuple(age, weight, color);
}
or by reference: 或参考:
std::tuple<int const&, int const&, string const&> getAllTheValues() const
{
return std::tie(age, weight, color);
}
Though you probably don't want to actually write this sort of thing. 虽然您可能实际上不想写这种东西。 Just pass the class itself around and use the single-getters you already have.
只需传递类本身,然后使用您已经拥有的单一获取方法即可。
Here's one solution nobody mentioned yet: 这是一个尚未提及的解决方案:
struct values { int age; int weight; string color; };
values getValues() const
{
return { this->age, this->weight, this->color };
}
You could pass by reference instead of returning a value for example: 您可以通过引用传递而不是返回值,例如:
void getValues(int & yrs, int & lbs, string & clr) const
{
yrs = this->age;
lbs = this->weight;
clr = this->color;
}
You could write a function that gets references as input like so: 您可以编写一个将引用作为输入的函数,如下所示:
void getAllTheValues(int& age, int& weight, std::string& color) {
age = this->age;
weight = this->weight;
color = this->color;
}
and use it like that 像那样使用
int age, weight;
string color;
myClass object();
object.getAllTheValues(age, weight, color);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.