error LNK2001: 未解析的外部符号“private: static class

问题描述 投票:0回答:4

error LNK2001: 未解析的外部符号“private: static class irrklang::ISoundEngine * GameEngine::Sound::_soundDevice” (?_soundDevice@Sound@GameEngine@@0PAVISoundEngine@irrklang@@A)

我不知道为什么会收到此错误。我相信我正在正确初始化。谁能伸出援手?

声音.h

class Sound
{
private:
    static irrklang::ISoundEngine* _soundDevice;
public:
    Sound();
    ~Sound();

    //getter and setter for _soundDevice
    irrklang::ISoundEngine* getSoundDevice() { return _soundDevice; }
//  void setSoundDevice(irrklang::ISoundEngine* value) { _soundDevice = value; }
    static bool initialise();
    static void shutdown();

声音.cpp

namespace GameEngine
{
Sound::Sound() { }
Sound::~Sound() { }

bool Sound::initialise()
{
    //initialise the sound engine
    _soundDevice = irrklang::createIrrKlangDevice();

    if (!_soundDevice)
    {
        std::cerr << "Error creating sound device" << std::endl;
        return false;
    }

}

void Sound::shutdown()
{
    _soundDevice->drop();
}

我在哪里使用声音设备

GameEngine::Sound* sound = new GameEngine::Sound();

namespace GameEngine
{
bool Game::initialise()
{
    ///
    /// non-related code removed
    ///

    //initialise the sound engine
    if (!Sound::initialise())
        return false;

任何帮助将不胜感激

c++ visual-c++ linker-errors static-members
4个回答
62
投票

把这个放进

sound.cpp

irrklang::ISoundEngine* Sound::_soundDevice;

注意: 您可能还想初始化它,例如:

irrklang::ISoundEngine* Sound::_soundDevice = 0;

static
,但非
const
数据成员应该在类定义之外和包含类的名称空间内定义。通常的做法是在翻译单元(
*.cpp
)中定义它,因为它被认为是一个实现细节。只有
static
const
整数类型可以同时声明和定义(在类定义内):

class Example {
public:
  static const long x = 101;
};

在这种情况下,您不需要添加

x
定义,因为它已经在类定义中定义。但是,在您的情况下,这是必要的。摘自 C++ 标准的 9.4.2 节

静态数据成员的定义应出现在包含成员类定义的命名空间范围内。


8
投票

最终,@Alexander 给出的答案解决了我自己代码中的类似问题,但并非没有经过几次尝试。为了下一位访问者的利益,当他说“将其放入 sound.cpp”时,非常清楚,这是对 sound.h 中已经存在的内容的补充。


0
投票

我对堆栈数组定义有同样的问题。所以,让我在这里简单地解释一下。

头文件中:

class MyClass
{
private:
    static int sNums[55]; // Stack array declaration
    static int* hNums;    // Heap array declaration
    static int num;       // Regular variable declaration
}

在 C++ 文件中

int MyClass::sNums[55] = {};          // Stack array definition
int MyClass::hNums[55] = new int[55]; // Heap array definition
int MyClass::num = 5;                 // Regular variable Initialization

0
投票

如果会用C++17,就可以声明

inline static
数据成员:

private:
inline static irrklang::ISoundEngine* _soundDevice;
© www.soinside.com 2019 - 2024. All rights reserved.