函数模板与 constexpr 函数
指“允许在常量表达式中被调用的函数”。只需把 constexpr
关键字放在返回类型前即可声明。
- 仅在需要常量表达式的上下文中才保证在编译期求值;否则可在编译期(如符合条件)或运行期求值。
- 隐式为
inline
;若要在编译期调用,编译器必须看到其完整定义,而不仅是前向声明。
consteval 函数
指必须在编译期求值的函数;其余规则与 constexpr 函数相同。
测验
问题 1
请在下列程序中适当位置添加 const
和/或 constexpr
:
#include <iostream>
// 从用户处获取塔高并返回
double getTowerHeight()
{
std::cout << "Enter the height of the tower in meters: ";
double towerHeight{};
std::cin >> towerHeight;
return towerHeight;
}
// 根据塔高与经过的秒数,返回球距地面的高度
double calculateBallHeight(double towerHeight, int seconds)
{
double gravity{ 9.8 };
// 使用公式 [ s = u·t + (a·t²)/2 ],其中初速度 u = 0
double distanceFallen{ (gravity * (seconds * seconds)) / 2.0 };
double currentHeight{ towerHeight - distanceFallen };
return currentHeight;
}
// 打印球距地面的高度
void printBallHeight(double ballHeight, int seconds)
{
if (ballHeight > 0.0)
std::cout << "At " << seconds << " seconds, the ball is at height: "
<< ballHeight << " meters\n";
else
std::cout << "At " << seconds << " seconds, the ball is on the ground.\n";
}
// 计算并打印当前球高
void printCalculatedBallHeight(double towerHeight, int seconds)
{
double ballHeight{ calculateBallHeight(towerHeight, seconds) };
printBallHeight(ballHeight, seconds);
}
int main()
{
double towerHeight{ getTowerHeight() };
printCalculatedBallHeight(towerHeight, 0);
printCalculatedBallHeight(towerHeight, 1);
printCalculatedBallHeight(towerHeight, 2);
printCalculatedBallHeight(towerHeight, 3);
printCalculatedBallHeight(towerHeight, 4);
printCalculatedBallHeight(towerHeight, 5);
return 0;
}
(答案见下方折叠区)