我有一个初学者c ++类的作业(见下面的问题),其中我被要求从单个函数传回2个值。我非常清楚我对如何使用函数的理解以及程序应该是什么的一般结构,但是我在如何将两个变量从函数传递回“main”时遇到了麻烦。
分配: 编写一个模拟飞机比赛的程序。该程序将显示一个表格,显示每秒两架飞机以千米/小时为单位的速度和以千米为单位的距离,直到其中一架飞机达到10公里。
这些是该计划的要求:
- 程序将使用具有以下参数的功能:时间和加速度。
- 该功能将传回两个数据项:速度和距离。
答案 0 :(得分:3)
你有两个选择(好吧,三个,但是我要留下指针)。
哪个选项最好取决于您的计划。如果这是一个没有从很多地方调用的一次性函数,那么你可以选择使用选项#1。我假设“速度”是指在加速“时间”之后达到的“恒定速度”。
void calc_velocity_profile(double accel_time,
double acceleration,
double &out_velocity, // these last two are
double &out_distance); // assigned in the function
如果这是一个更通用的功能和/或许多客户将调用的功能,我可能更喜欢选项#2。
struct velocity_profile {
double velocity;
double distance;
};
velocity_profile calc_velocity_profile(double accel_time, double acceleration);
一切都相同,我更喜欢选项1.给定选择,我喜欢一个函数,它返回一个值而不是一个改变其输入的函数。
答案 1 :(得分:3)
2017年更新:这在C ++核心指南中讨论:
F.21 To return multiple "out" values, prefer returning a tuple or struct
但是,由于命名的,与顺序无关的访问被封装并可重用为显式强类型,因此我倾向于在元组上返回结构。
在返回bool
和T
的特殊情况下,T
仅在bool
为true
的情况下填写,请考虑返回std::optional<T>
。有关详细讨论,请参阅this CPPCon17 video。
结构版本:
struct SpeedInfo{
float speed;
float distance;
};
SpeedInfo getInfo()
{
SpeedInfo si;
si.speed = //...
si.distance = //...
return si;
}
这样做的好处是可以获得具有命名访问权限的封装类型。
参考版本:
void getInfo(float& speed, float& distance)
{
speed = //...
distance = //...
}
您必须传入输出变量:
float s;
float d;
getInfo(s, d);
指针版本:
void getInfo(float* speed, float* distance)
{
if(speed)
{
*speed = //...
}
if(distance)
{
*distance= //...
}
}
传递输出变量的内存地址:
float s;
float d;
getInfo(&s, &d);
指针版本很有趣,因为您只需传递一个nullptr
/ NULL
/ 0
来处理您不感兴趣的内容;当你使用这样一个可能占用大量参数但对所有输出值不感兴趣的函数时,这会很有用。 e.g:
float d;
getInfo(nullptr, &d);
这是你不能用引用做的事情,尽管它们更安全。
答案 2 :(得分:1)
C ++中已经存在这样一种名为std :: pair的数据结构。它在标题<utility>
中声明。因此该函数可以采用以下方式
std::pair<int, int> func( int time, int acceleration )
{
// some calculations
std::pair<int, int> ret_value;
ret_value.first = speed_value;
ret_value.second = distance_value;
return ( ret_value );
}