【问题标题】:Error when calling static method c++调用静态方法c++时出错
【发布时间】:2018-05-14 03:44:20
【问题描述】:

考虑以下代码:

Automobile.h

class Automobile
{

    static string m_stCityCode;

    static bool CheckCityCode(const Automobile& obj);

};

汽车.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:\Users\zhivko.rusev\Documents\Visual
Studio 2015\Projects\myPro\myPro\Calls.obj  1   "

对于解决此问题的所有帮助,我将不胜感激。提前致谢!

【问题讨论】:

  • 你需要在某处定义你的静态成员。它应该在您最喜欢的 C++ 书籍中提及。 (顺便说一句,你的比较总是正确的。)

标签: function methods static boolean


【解决方案1】:

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

要定义它,在单个编译单元(即非头源文件)中,只需在包含头文件后在文件范围内添加一行

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

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

除了您所询问的问题之外,您的代码中还有其他问题,但我认为这只是反映您遗漏了信息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-31
    • 1970-01-01
    • 1970-01-01
    • 2012-08-02
    • 2018-03-14
    • 1970-01-01
    • 2011-05-15
    • 2018-09-12
    相关资源
    最近更新 更多