简体   繁体   English

C ++未解析的外部符号

[英]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 嗨iam begginer在c ++我有静态方法的类,我无法访问它,它会引发我一个错误

    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. 因为它是static ,所以这行只声明 name - 你也需要定义它。 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++ . 我想你应该用gcc编译,当你应该用g++进行编译时。 See What is the difference between g++ and gcc? 看看g ++和gcc有什么区别? for more on this. 了解更多。

You also need to add string CPractice::name; 您还需要添加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. 由于name是静态数据成员,因此您应该初始化它:)并且不要指望与默认实例相关的构造函数。

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM