c++如何访问另一个类中的私有静态变量

C++ How to access private static variable in another class

本文关键字:变量 静态 另一个 何访问 访问 c++      更新时间:2023-10-16

我试图从另一个类访问私有静态变量(*PhysicsEngine::_world->setDebugDrawer(&debugDraw);*)。

第一课:

namespace GameEngine
{
    class PhysicsEngine
    {
    private:
        // Pointer to Bullet's World simulation
        static btDynamicsWorld* _world;

第二个类:

bool Game::initialise()
    {
        _device = irr::createDevice(irr::video::EDT_OPENGL,
                                    _dimensions,
                                    16,
                                    false,
                                    false,
                                    false,
                                    &inputHandler);
        if(!_device)
        {
            std::cerr << "Error creating device" << std::endl;
            return false;
        }
        _device->setWindowCaption(_caption.c_str());
    //////////////
    DebugDraw debugDraw(game._device);
    debugDraw.setDebugMode(
    btIDebugDraw::DBG_DrawWireframe |
    btIDebugDraw::DBG_DrawAabb |
    btIDebugDraw::DBG_DrawContactPoints |
    //btIDebugDraw::DBG_DrawText |
    //btIDebugDraw::DBG_DrawConstraintLimits |
    btIDebugDraw::DBG_DrawConstraints //|
    );
    PhysicsEngine::_world->setDebugDrawer(&debugDraw);

如果我使_world公开,我得到未处理的异常在0x00EC6910在Bullet01.exe: 0xC0000005:访问违规读取位置0x00000000。

在物理引擎类中公开一些静态函数,该函数返回私有静态变量_world的引用或指针,然后调用该静态函数。

PhysicsEngine::getWorld()->setDebugDrawer(&debugDraw);

显示下面的方法

static btDynamicsWorld* getWorld() { return _world; }

在这个类中声明这个类为Friend。然后该类的成员函数可以访问这个私有静态成员。