需要有关函数别名的帮助

Need help regarding alias for a function

本文关键字:别名 帮助 函数      更新时间:2023-10-16

所以我正在用 c++ 做一个作业,告诉我们要为函数使用别名,或者至少为函数指针使用别名(据我所知)。这不被视为"教学大纲"(我们需要学习的,不知道这是否是正确的词),因此没有被讲授。

为了更清楚地理解任务,我有一个带有函数draw()的类"车辆",可以更新车辆的速度并将其绘制到屏幕上。然后我们被告知使用函数指针将draw()的输入部分移动到一个单独的函数。这个单独的函数应该是类的私有成员,在构造函数中初始化。然后我们被告知使用这个"别名"来使代码更易于阅读:

using drivingAlgorithm = std::pair<double,double> ( PhysicsState ps,
const std::vector<std::pair<double,double>>& goals,
int currentGoal);

这应该放在不同的 .h 文件中,其中还定义了结构PhysicsState。我的问题是,如何使用这个"别名"?更具体地说,我在哪里定义我使用别名的函数的实际主体?我似乎无法在我们的教科书中找到答案,也不是通过搜索谷歌。

我想你可能弄错了棍子的一端。这里没有什么复杂的。也许一个简短的样本会有所帮助。

include <vector>
#include <utility>
class PhysicsState
{
};
using drivingAlgorithm = std::pair<double, double>(PhysicsState ps,
const std::vector<std::pair<double, double>>& goals,
int currentGoal);
class Vehicle
{
public:
Vehicle(drivingAlgorithm da) : _da(da) {}
private:
drivingAlgorithm _da;
};
std::pair<double, double> my_algorithm(PhysicsState ps,
const std::vector<std::pair<double, double>>& goals,
int currentGoal)
{
return std::make_pair(0.0, 0.0);
}
int main()
{
Vehicle v(my_algorithm);
}

using x = ...只是建立一个类型别名,而不是函数别名(这样的东西不存在)。在本例中,类型是函数类型。但无论如何,您都像使用任何其他类型一样使用类型别名。