开发者

Singleton Inheritance Linker Error

开发者 https://www.devze.com 2023-04-12 12:51 出处:网络
I\'m new with C++, and I got this linker error, LNK2001: unresolved external symbol \"private: static class DebugLog Singleton::instance\" (?instance@?$Singleton@VDebugLog@@@@0VDebugLog@@A)

I'm new with C++, and I got this linker error,

LNK2001: unresolved external symbol "private: static class DebugLog Singleton::instance" (?instance@?$Singleton@VDebugLog@@@@0VDebugLog@@A)

And here is the problematic codes:

template<typename T>
class Singleton {
public:
    static T& getInstance() {
        return instance;
    }
private:
    static T instance;
};

class DebugLog : public Singleton<DebugLog> {
public:
    void doNothing() {}
};

void main() {
    DebugLog::getInstance().doNothing();
}

Could anybody tell me how I can fix that linker error without losing the Singleto开发者_开发技巧n inheritance in DebugLog?

Thank you.


You missed:

template<typename T>
T Singleton<T>::instance;

Insert those lines after your class definition.

In order to initialize a static data-member we must include a formal definition outside the class, in the global scope.

For more information read this link (Section: Static members)


You need to actually define an instance of the static variable DebugLog Singleton::instance somewhere in your code, you just declared that it exists somewhere, but never actually created it to really exist. The linker is looking for it.

Here's some examples of how to do it right.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号