简体   繁体   中英

Unresolved external symbol when using static

I am new to c++. I started now playing with classes and I am having a noob problem with statics.

class Test
{
public:
    Test(){};
    ~Test(){};
    static void test();
    static Helper* helper;
};

void Test::test()
{
    Object obj = Test::helper->getObject();
    //...
}

When I try to compile it gives the error:

main.obj : error LNK2001: unresolved external symbol "public: static class Helper* Test::helper" (?helper@Test@@2PAVHelper@@A)

What is wrong with my code?

The first answer is correct. The reason behind this is that you need to allocate memory for static objects outside the class definition. If you define the the class in a header file, and include it in several cpp files, the compiler doesn't know where and how you want to create the object that 'helper' points to.

you need to define Test::helper. Write something like this outside the class:

Helper* Test::helper = new Helper;

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