使用相同类型的静态非空指针初始化后,指向自定义类型的静态指针保持 nullptr [英] static Pointer to Custom Type stays nullptr after initialization with static not-null pointer of same Type
问题描述
我有两个命名空间,每个命名空间都有一个指向其中一个命名空间内的类 Window 的指针.
I have two namespaces with each a pointer to a class Window inside of one of the namespaces.
Graphic.h
namespace Graphic {
//...
class Window;
//...
void init();
static Window* window;
}
App.h
namespace App{
//...
static Graphic::Window* mainWindow = nullptr;
//...
void init();
void setupGraphic();
//...
}
我正在尝试使用 static Window* Graphic::window
初始化 static Window* App::mainWindow
I am trying to initialize the static Window* App::mainWindow
with the static Window* Graphic::window
Window.h
#include "Graphic.h"
#include <SDL\SDL.h>
class Graphic::Window
{
public:
Window(const char* pName = "OpenGL Window",
unsigned int pWidth = 1000, unsigned int pHeight = 700);
~Window();
const char* name;
unsigned int width;
unsigned int height;
SDL_Window* window;
};
Graphic::window 正在像这样初始化
Graphic.cpp
#include "Graphic.h"
void Graphic::init(){
window = new Window("Engine");
}
在初始化之后,我尝试用 Graphic::window
And after this initialization i try to initialize the (static Window*)App::mainWindow
with Graphic::window
App.cpp
#include "App.h"
#include <Graphic\Graphic.h>
#include <Graphic\Window.h>
void App::setupGraphic()
{
Graphic::init();
App::mainWindow = Graphic::window;
}
但是 App::mainWindow
保持 nullptr,即使 Graphic::window
已经成功初始化并且已经在 Graphic::init()
.没有编译警告/错误,我得到的只是一个异常App::mainWindow was nullptr."
But App::mainWindow
stays nullptr, even though Graphic::window
has successfully been initialized and has already been worked with in Graphic::init()
. There are no compilation warnings/errors, all i get is an exception "App::mainWindow was nullptr."
推荐答案
在Graphic.h"中,你有
In "Graphic.h", you have
static Window* window;
此语句包含在将 #include Graphic.h
的每个翻译单元 (.cpp) 中.因此,每个单元都有其自己的变量window
.然后发生的是 Graphic.cpp
分配自己的 window
,但是 main.cpp
找到自己的变量 window
不变.
This statement is included in every translation unit (.cpp) that will #include Graphic.h
. Therefore each unit will have its own variable window
. What happens then is that Graphic.cpp
assigns its own window
, but main.cpp
find its own variable window
unchanged.
你应该做的是:
在Graphic.h中,声明window
但不定义它:
In Graphic.h, declare window
but don't define it:
extern Window* window;
并且只定义一次,在 Graphic.cpp 中:
And define it only once, in Graphic.cpp:
Window* Graphic::window = nullptr;
这样所有的翻译单元都会引用同一个全局变量window
.
This way all the translation units will refer to the same global variable window
.
您应该对 App.h 中定义的变量 Graphic::Window* mainWindow
执行相同的操作.
You should do the same for the variable Graphic::Window* mainWindow
defined in App.h.
extern Graphic::Window* mainWindow; // <-- in App.h
和
Graphic::Window* App::mainWindow = nullptr; // <-- in App.cpp
这篇关于使用相同类型的静态非空指针初始化后,指向自定义类型的静态指针保持 nullptr的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!