我是一个初学者,遇到上述错误。以下是来自三个文件的完整代码ball.h
:
#ifndef BALL_H
#define BALL_H
namespace
{
inline constexpr double gravity{ 9.81 };
}
double getInitialHeight(void);
double calculateHeight(double, int);
void printHeight(double, int);
void calculateAndPrintHeight(double, int);
void solve(void);
#endif
ball.cpp
:
#include "ball.h"
#include <iostream>
double getInitialHeight()
{
std::cout << "Enter the height of the tower in meters ";
double initialHeight{};
std::cin >> initialHeight;
return initialHeight;
}
double calculateHeight(double initialHeight, int secondsPassed)
{
double distanceFallen{ BALL_H::gravity * secondsPassed * secondsPassed / 2.0 };
double currentHeight{ initialHeight - distanceFallen };
return currentHeight;
}
void printHeight(double height, int secondsPassed)
{
if (height > 0.0)
{
std::cout << "At " << secondsPassed << " seconds, the ball is at height\t" << height << " meters.\n";
}
else
{
std::cout << "At " << secondsPassed << " seconds, the ball is on the ground.\n";
std::exit(0);
}
}
void calculateAndPrintHeight(double initialHeight, int secondsPassed)
{
double height{ calculateHeight(initialHeight, secondsPassed) };
printHeight(height, secondsPassed);
}
void solve()
{
const double initialHeight{ getInitialHeight() };
int secondsPassed{ 0 };
while (true)
{
calculateAndPrintHeight(initialHeight, secondsPassed);
secondsPassed++;
}
}
Solution.cpp
(解决方案中的主项目文件):
#include <iostream>
#include "ball.h"
int main()
{
solve();
return 0;
}
我知道此问题是由于链接器找不到对的引用引起的solve()
。但是,我不确定如何解决该问题。一种简单的解决方案是仅包含ball.cpp
而不是ball.h
:
#include <iostream>
#include "ball.cpp"
int main()
{
solve();
return 0;
}
这段代码有效,但是我想知道如何使用标头,因为我不确定这是否是一个好习惯。
编辑:这是错误列表:
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句