嗨,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 ==========
这是我的代码
#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;
由于它是
static
,所以此行仅声明name
-您也需要对其进行定义。只需将其放在您的类定义下面:string CPractice::name;
如果最终将类移动到相应的 header 和实现文件,请确保将此定义放在实现文件中。它只能在单个翻译单元中定义。