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:usersinnersoftdocumentsvisual studio 2012ProjectsCPracticeDebugCPractice.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.


你只在类中声明了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;
链接地址: http://www.djcxy.com/p/85756.html

上一篇: 与cuda有关的libstdc ++。so.6的链接器问题

下一篇: C ++无法解析的外部符号