简体   繁体   中英

C++ unresolved external symbol

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, Configuration: Debug Win32 ------
1>  Source.cpp
1>Source.obj : error LNK2001: unresolved external symbol "private: static class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > CPractice::name" (?name@CPractice@@0V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@A)
1>c:\users\innersoft\documents\visual studio 2012\Projects\CPractice\Debug\CPractice.exe : fatal error LNK1120: 1 unresolved externals
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

and here is my code

#include <iostream>
#include <stdio.h>
#include <cstdlib>
#include <string>

using namespace std;

class CPractice
{
    public:
        static void setName(string s)
        {
            name = s;
        }
        static string getName()
        {
            return name;
        }
    private:
        static string name;
};


int main()
{


    CPractice::setName("Name");
    cout << "\n" << CPractice::getName();
    system("PAUSE");
    return EXIT_SUCCESS;
}
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.

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.

您只在类中声明了name ,静态变量需要在类之外定义:

string CPractice::name ="hello" ;

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;

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