c++ - 多个定义,如何原型(prototype) std::map?

标签 c++ class forward-declaration

我知道发生了什么事,但我不知道如何解决这个问题:

main.cpp

#include "Win32.h"

int main () {
    return 0;
}

Win32.h

#include <windows.h>
#include <map>

#ifndef WIN32_H_
#define WIN32_H_

namespace W32 {

class Win32;                        // Pre-Declaration
std::map<HWND, Win32 *> windowMap;  // Handle to Class instance mapping

class Win32 {
    public:

        Win32();
        virtual ~Win32();

    protected:

    private:

};  // Class Win32

} // namespace W32

#endif // WIN32_H_

Win32.cpp

#include "Win32.h"


namespace W32 {

Win32::Win32() {
}

Win32::~Win32() {
}

} /* namespace W32 */

错误消息:

    src\Win32.o: In function `Win32':
    D:\Dev\Projects\Eclipse\OpenGL3\Debug/../src/Win32.cpp:7: multiple definition of `W32::windowMap'
    src\main.o:D:\Dev\Projects\Eclipse\OpenGL3\Debug/../src/main.cpp:14: first defined here

好的,我明白了 std::map<HWND, Win32 *> windowMap;出现在多个文件中,并且由于它包含在多个文件(main.cpp/Win32.cpp)中,因此导致它被重新定义。我对 std::map 还是有点陌生​​。我需要做的是原型(prototype)windowMap ,但我不知道如何?我以为这是我捕获这段代码的时候。 Win32 类需要能够使用它,但必须声明它才能这样做,但我所拥有的并不是这样做的方法,我不知道如何寻找正确的方法有关如何正确转发声明的信息 std::map<HWND, Win32 *> windowMap .

最佳答案

std::map<HWND, Win32 *> windowMap; 

是一个定义,因此您违反了单一定义规则。您需要使变量extern:

extern std::map<HWND, Win32 *> windowMap; 

并在单个实现文件中定义它:

Win32.h

#include <windows.h>
#include <map>

#ifndef WIN32_H_
#define WIN32_H_

namespace W32 {
   class Win32;                        // Pre-Declaration
   extern std::map<HWND, Win32 *> windowMap;  // Handle to Class instance mapping
   //...
};  // Class Win32

} // namespace W32

#endif // WIN32_H_

Win32.cpp

#include "Win32.h"
namespace W32 {
   std::map<HWND, Win32 *> windowMap;  // Handle to Class instance mapping
   //...
} /* namespace W32 */

关于c++ - 多个定义,如何原型(prototype) std::map?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10777023/

相关文章:

重载运算符的 C++ 前向声明

c++ - 在 constexpr 函数中切换

c++ - 如何使Qt生成makefile而不需要qmake依赖

java - 无法在类对象的 ArrayList 中存储值。 (代码已编辑)

html - 当前浏览器对.class Name.和ClassName的支持是什么?

typedef 结构的 C 前向声明

c - 在 C 中具有前向声明的 typedef 结构

c++ - Qt3D骨骼动画

c++ - Windows Phone 8.1 是否支持 select() 套接字函数?

c++ - 在类语法帮助中比较对象;