简体   繁体   中英

Unresolved externals of creating a static instance in C++

I have produced this C++ code:

class TestInstance
{
    public:
        TestInstance();
        ~TestInstance();
        static TestInstance& GetInstance();

    private:
        static TestInstance* testInstance;
};

But I got this error when compiling:

error LNK2001: unresolved external symbol "private: static class TestInstance* TestInstance::testInstance" (?testInstance@TestInstance@@0PAV1@A)

fatal error LNK1120: 1 unresolved externals

Any idea?

Yes, initialize the static member in an implementation file.

//TestInstance.cpp
TestInstance* TestInstance::testInstance = NULL; 

You need to initialize static member variables in an implementation file. Why is it necessary.

Since static member variables are not part of the individual objects (or instances) of that class, They have same value of all the objects of that class. Thats why static member objects are not given memory in individual objects of that class. So, how the space will be allocated for them. Compiler doesnt know. So, you will have to define them in an implementation file, so that compiler can allocate space for these members in that transalation unit.

For your class, if you will do sizeof(a), where a is an object of the class, you will see that size is being shown as one. Since there will be no space for testInstance in the object of the class. And size cant be zero, so it will be one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM