6

嗨,我是 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 ==========

这是我的代码

#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;
}
4

4 回答 4

18
static string name;

事实上static,这一行只声明 name- 你也需要定义它。只需将其放在您的类定义下方:

string CPractice::name;

如果您最终将您的类移动到相应的头文件和实现文件中,请确保将此定义放在实现文件中。它应该只在一个翻译单元中定义。

于 2013-03-12T19:20:09.347 回答
1

我认为您正在尝试使用 进行编译gcc,而您应该使用g++. 请参阅g++ 和 gcc 有什么区别?了解更多信息。

您还需要string CPractice::name;在您的类定义下方添加。

于 2013-03-12T19:22:06.607 回答
1

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

string CPractice::name ="hello" ;
于 2013-03-12T19:22:10.920 回答
1

由于 name 是一个静态数据成员,您应该对其进行初始化:) 而不是指望与默认实例相关的构造函数。

在类定义之后添加它(是的,我知道它令人困惑,因为您的成员是私有成员,但这只是一个初始化):

string CPractice::name;
于 2013-03-12T19:24:31.967 回答