我不断收到一条错误消息,提示“'void Engine::start(Tank&)' 的原型(prototype)与'Engine' 类中的任何原型(prototype)都不匹配”此外,它还提示“'Tank' 尚未声明”,所有这些在 Engine 类中处于相同的“启动”功能。
//Engine.h
#ifndef ENGINE_H
#define ENGINE_H
using namespace std;
class Engine {
public:
Engine(int);
~Engine() {};
void setTrip(int tr);
int getTrip();
bool isStarted();
void start(Tank &inTank);
void stop();
protected:
bool started;
int trip, numCyl;
};
#endif /* ENGINE_H */
//Engine.cpp
using namespace std;
#include "Engine.h"
#include "Tank.h"
这个 .cpp 还有更多内容,但这是错误所在的函数 正在发生。
void Engine::start(Tank &inTank) {
if(inTank.isEmpty()) {
cout << "Engine cannot start\n";
started = false;
}
else {
cout << "Engine started\n";
started = true;
}
}
而我这里的main就是用来测试这两个类的。
#include "Tank.h"
#include "Engine.h"
#include <cstdlib>
using namespace std;
int main()
{
Tank t(12);
Engine e(4);
e.start(t);
e.stop();
t.refuel();
e.start(t);
e.stop();
return 0;
}
然后我将添加我的 Tank 类。
#ifndef TANK_H
#define TANK_H
using namespace std;
class Tank {
public:
Tank(float);
virtual ~Tank();
void consumeFuel(float);
float getFuel();
virtual void refuel();
bool isEmpty();
int getNumTanks();
float getTankCapacity();
void setFuel(float fl);
protected:
static int numTanks;
const float tankCapacity;
float fuel;
bool empty;
};
#endif /* TANK_H */
坦克.cpp
using namespace std;
#include "Tank.h"
#include "Engine.h"
//creates tank with certain capacity taken from parameter.
Tank::Tank(float inCap) {
Tank::tankCapacity(inCap);
}
//I completed the rest of the functions with no errors... so far.lul
最佳答案
每当 header 中的引用或指针使用类时,您都需要转发声明该类而不是包含整个 .h 文件。
因此在您的情况下,您只需要在 Engine.h 中转发声明类 Tank 并在 Engine.cpp 中包含 Tank.h。
//Engine.h
#ifndef ENGINE_H
#define ENGINE_H
//Forward Declaration
class Tank;
using namespace std;
class Engine {
public:
Engine(int);
~Engine() {};
void setTrip(int tr);
int getTrip();
bool isStarted();
void start(Tank &inTank);
void stop();
protected:
bool started;
int trip, numCyl;
};
#endif /* ENGINE_H */
关于c++ - 函数原型(prototype)与 C++ 类中的任何原型(prototype)都不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29787988/