Static members and LNK error in C++

前端 未结 3 1143
南方客
南方客 2021-01-27 16:30

I have a class that has a static member, which I want to use in the class constructor, but the code doesn\'t compile, and I\'m left with these errors:

fat

相关标签:
3条回答
  • 2021-01-27 16:58

    In your .cpp you need to add:

    Collection<A*> A::collection;
    

    The .h only declared that there would be a copy somewhere. You need to provide that copy in the .cpp.

    0 讨论(0)
  • 2021-01-27 17:05

    You need to add

    Collection<A*> A::collection;
    

    to your a.cpp file.

    0 讨论(0)
  • 2021-01-27 17:08

    alternatively, if you don't want to put that line in a cpp file, you can use a static method which returns a reference to a static instance... i.e.

    class A
    {
    public:
      static Collection<A*>& collection()
      {
        static Collection<A*> singleInstance;
        return singleInstance;
      }
    };
    
    0 讨论(0)
提交回复
热议问题