调用静态方法C 时出错



考虑以下代码:

automobile.h

class Automobile
{
    static string m_stCityCode;
    static bool CheckCityCode(const Automobile& obj);
};

automobile.cpp

bool Automobile::CheckCityCode(const Automobile& obj)
{
    return m_stCityCode == obj.m_stCityCode;
}

int main()
{
//do something
}

我得到以下错误

"Severity   Code    Description Project File    Line    Suppression State
Error   LNK2001 unresolved external symbol "public: static class
std::basic_string<char,struct std::char_traits<char>,class
std::allocator<char> > Automobile::m_stCityCode"
(?m_stCityCode@Automobile@@2V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@A)    myPro   C:Userszhivko.rusevDocumentsVisual
Studio 2015ProjectsmyPromyProCalls.obj  1   "

我感谢解决此问题的所有帮助。预先感谢!

需要定义静态成员。错误消息是链接器告诉您不是的方式。您的代码声明静态成员,但没有定义。

要定义它,在单个汇编单元(即非标题源文件)中只需在文件范围上添加一条线,包括标题文件

#include "Automobile.h"
std::string Automobile::m_stCityCode = "";   // change the initialiser to whatever suits

在一个汇编单元中进行此操作。定义符号是必要的。多个定义(例如,在项目中的多个源文件中)将导致链接器抱怨多次定义符号。

您的代码中还有其他问题,如您所要求的,但我认为这只是反映您已遗漏了信息。

最新更新