1

请在这里给我一个提示:

class UIClass
{
public:
    UIClass::UIClass();
};

#ifndef __PLATFORM__
#define __PLATFORM__
    UIClass Platform;
#else
    extern UIClass Platform;
#endif

我包括这两次并得到:

LNK2005 - 平台已在 .obj (MSVS13) 中定义。

您可以猜到,这个想法是只定义一次平台。为什么会#ifndef#define失败?我应该如何解决这个问题?

4

1 回答 1

8

#define's 是本地翻译单元,但定义不是。您需要放入extern UIClass Platform;标题和UIClass Platform;实现文件中。

如果你真的想在你的标题中有定义,你可以使用一些模板类魔法:

namespace detail {
    // a template prevents multiple definitions
    template<bool = true>
    class def_once_platform {
        static UIClass Platform;
    };

    // define instance
    template<bool _> def_once_platform<_> def_once_platform<_>::Platform;

    // force instantiation
    template def_once_platform<> def_once_platform<>::Platform;
}

// get reference
UIClass& Platform = detail::def_once_platform<>::Platform;
于 2014-01-06T17:09:44.577 回答