C++ unresolved external symbol

前端 未结 4 1516
说谎
说谎 2021-01-12 21:04

Hi iam begginer at c++ i have class with static methods and i cant access them it throws me an error

    1>------ Build started: Project: CPractice, Confi         


        
相关标签:
4条回答
  • 2021-01-12 21:33

    You only declared name in the class, static variables need to be defined like so outside of the class:

    string CPractice::name ="hello" ;
    
    0 讨论(0)
  • 2021-01-12 21:42
    static string name;
    

    As it is static, this line only declares name - you need to define it too. Simply place this below your class definition:

    string CPractice::name;
    

    If you end up moving your class to a corresponding header and implementation file, make sure you place this definition in the implementation file. It should only be defined in a single translation unit.

    0 讨论(0)
  • 2021-01-12 21:43

    Since name is a static data member you should initialize it :) and not count on the default instance related constructor.

    Add this after the class definitions (yep, I know its confusing since your member is a private one, but this is only an initialization) :

    string CPractice::name;
    
    0 讨论(0)
  • 2021-01-12 21:43

    I think you're trying to compile with gcc, when you should be compiling with g++. See What is the difference between g++ and gcc? for more on this.

    You also need to add string CPractice::name; below your class definition.

    0 讨论(0)
提交回复
热议问题