C++ Extern Class Declaration

后端 未结 3 1499
有刺的猬
有刺的猬 2020-12-10 17:59

Edit: Ok I wrote a little test program to show here. Here is the Source Code.

main.cpp:

#include \"core.h\"

Core core;

int main()
{
  core.coreFunc         


        
相关标签:
3条回答
  • 2020-12-10 18:34

    Either you forgot to define core's default constructor, or core cannot be trivially default constructed (due to having a base or member that does not have a default constructor.

    To core, add:

    class Core {
        Window window;
    
        Core() {} //add this line
        void someFunction()
        {
            window.doSomething();
        }
    }
    

    To window, add:

    class Window
    {
        Window() {} //add this line
        void someFunction()
        {
            core.doSomething();
        }
    }
    

    If either fails to compile, you'll have pinned down the problem a little more

    EDIT:

    Well now that the error message was clarified, I see the error right off. Window.h requires Core core to be defined, and Core.h requires Window to be defined. The solution is to do as vz0 suggested from the get go. Move the definition of Window::someFunction to window.cpp (and I feel the need to go apologize to vz0)

    0 讨论(0)
  • 2020-12-10 18:36

    You are including the window.h header before the "extern Core core;" line. Try adding that line just before the class Window line on the window.h header:

    window.h

    #ifndef WINDOW_H__
    #define WINDOW_H__
    
    extern Core core;
    
    class Window
    {...}
    

    Instead of using Core as a global variable, you can move core as a static member of the Core class. This is called the Singleton pattern.

    main.cpp

    #include "core.h"
    
    int main()
    {
      Core* core = Core::getInstance();
    
      core->coreFunction();
    }
    

    core.h

    #include "window.h"
    
    class Core
    {
    public:
      static Core* getInstance() { return &coreInstance; }
      void someFunction();
    
    private:
      static Core coreInstance;
      Window window;
    };
    

    core.cpp

    #include "core.h"
    
    Core Core::coreInstance;
    
    void Core::someFunction()
    {
      window.doSomething();
    }
    

    window.h

    class Window
    {
      void someFunction();
    };
    

    window.cpp

    #include "window.h"
    #include "core.h"
    
    void Window::someFunction()
    {
      Core* core = Core::getInstance();
    
      core->doSomething();
    }
    
    0 讨论(0)
  • 2020-12-10 18:45

    I think I found your problem. In the definition header file the "Core" class is declared as "core". Remember, caps makes a big difference.

    0 讨论(0)
提交回复
热议问题