简体   繁体   中英

C++ undefined error for using function in .cpp file that is defined in a different .cpp file?

I need to use the Display function defined in Dungeon.cpp (with a header in Dungeon.h) in DungeonLayer.cpp. Visual studio is giving the error message: identifier "Display" is undefined

    //DungeonLayer.h 
    #ifndef DUNGEON_LAYER
    #define DUNGEON_LAYER

    #include "Dungeon.h"
    #include <iostream>
    class dungeonLayer
    public: 
       void setItem(); 
    #endif 



      //DungeonLayer.cpp
      #include "DungeonLayer.h"

      void dungeonLayer::setItem()
       { 
         Display(); //error, visual studio says Display() is undefined
       }


    //Dungeon.h 
    #include <iostream>
    #ifndef DUNGEON_H
    #define DUNGEON_H
    class Dungeon
    public:
      void Display(); 
    #endif

//Dungeon.cpp
#include "Dungeon.h"
void Dungeon::Display()
{
  std::cout << "Goblin"; 
}

Since Display() is declared as a member function, so you need an instance of Dungeon in order to operate it. Your code should look something like:

dungeon.Display();

Where dungeon was previously initialized as Dungeon dungeon .

If Display() is not supposed to be a member function you must declare it as a static function so it can be called independently.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM