c++中在方法返回中组合多个值
Combining multiple values in method return in C++
我想看看是否有可能以相同的方式组合多个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);
相关文章:
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- 什么时候在C++中返回常量引用是个好主意
- 你能重载对象变量名本身返回的内容吗
- 为什么 Serial.println(<char[]>);返回随机字符?
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 如何获取std::result_of函数的返回类型
- QueryWorkingSet总是返回false
- (C++)分析树以计算返回错误值的简单算术表达式
- 当返回语句时,逗号运算符、大括号初始化列表和 std::unique_ptr 组合在一起
- 在C++中将返回unique_ptr和shared_ptr的两个工厂方法组合为一个
- 返回 sum 的数组中元素的组合
- DropDownList 组合上的 SendDlgItemMessage CB_GETLBTEXT 返回单个字母
- "无法封送'返回值':无效的托管/非托管类型组合",同时使用字符串数组封送委托
- 组合 std::forward、std::move 和 voltile 时出现意外的返回类型
- 我们如何组合在C++中返回多个值的函数
- Int作为一个随机的7位组合返回
- c++模板与STL返回类型的组合
- c++中在方法返回中组合多个值
- 算术和赋值操作符重载-返回值,范围,组合表达式
- 将多个对象组合成一个返回对象