函数的原型与类C++中的任何原型都不匹配

prototype for function does not match any in class C++

本文关键字:原型 任何 不匹配 函数 C++      更新时间:2023-10-16

我不断收到一个错误,说"'void Engine::start(Tank&)'的原型与类'引擎'中的任何原型都不匹配" 此外,它说"'Tank'尚未声明",所有这些都在引擎类中处于同一函数'start'。

    //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 startn";
                 started = false;
           }
           else {
                 cout << "Engine startedn";
                 started = true;
           }
     }

我在这里的主要内容是用于测试这两个类。

    #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;
     }

我将添加我的坦克类。

    #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

每当引用或指针在标头中使用类时,您需要转发声明该类,而不是包含整个.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 */

将 Tank 类声明移到引擎类上方