简体   繁体   English

我如何使用 function 返回成员数据的地址

[英]how do i return an address of a member data by using a function

i have my Engine class that contains the SDL_renderer* and I've been trying to get its address by using a function getRenderer but it returns null beside the fact that i have already initialize it (renderer) in the Engine.cpp我有我的引擎 class 包含 SDL_renderer* 并且我一直试图通过使用 function getRenderer 来获取它的地址,但它返回 null 实际上已经初始化了它。

class Engine
{
    public:
      SDL_Renderer* GetRenderer() { return m_renderer; } // null

      Engine() {}
      ~Engine() {}
private:
    bool m_Running = true;

   SDL_Window* m_window;
   SDL_Renderer* m_renderer;
 };


bool Engine::init()
{
   // initialize SDL
   if (SDL_Init(SDL_INIT_EVERYTHING) >= 0)
   {
      // if succeeded create our window
      m_window = SDL_CreateWindow("the title", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
          SDL_WIDTH, SDL_HEIGHT, false);

      Engine* engine = new Engine();
      std::cout << engine->GetRenderer() << std::endl;
      if (m_window != nullptr)
      {
          std::cout << "entering this";
          m_renderer = SDL_CreateRenderer(m_window, -1, 0);
      }
      else
      {
          return false; // sdl could not initialize
      }
      std::cout << m_renderer<< std::endl; // this is not null
      std::cout << engine->GetRenderer()<<std::endl; // this is null

      textureManager = new TextureManager();
      textureManager->Load("tree", "Assets/tree.png"); // tree for tree texture
      m_Running = true;
      return true;
  }
 }

Usually, when you run your C++ app in debug mode, it "clears" (set's to 0) all the uninitialized variables (not necessarily BTW).通常,当您在调试模式下运行 C++ 应用程序时,它会“清除”(设置为 0)所有未初始化的变量(不一定是 BTW)。 If you try to compile and run in release mode, you might get a non-zero value from the function.如果您尝试在发布模式下编译和运行,您可能会从 function 中获得一个非零值。 That's why it is always recommended and necessary to initialize your variables in the constructor.这就是为什么总是建议并且必须在构造函数中初始化变量的原因。 Even more, if you have a member raw pointer, you should be very careful, and consider having proper constructors and destructors.更重要的是,如果你有一个成员原始指针,你应该非常小心,并考虑使用适当的构造函数和析构函数。

Edit编辑

In your case, at least, I would suggest to initialize the variables and set them to be nullptr in the constructors initializer-list and then call Init directly from the constructor.至少在您的情况下,我建议初始化变量并将它们设置为构造函数 initializer-list 中的nullptr ,然后直接从构造函数调用Init

Maybe, there's a better solution, but this can be considered as a quick fix.也许,有一个更好的解决方案,但这可以被认为是一个快速修复。

Edit 2编辑 2

Worths to be mentioned the comment below: DONT FORGET ABOUT COPY AND MOVE CONSTRUCTORS值得一提的是下面的评论:不要忘记复制和移动构造函数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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