对类的公共方法/变量的未定义引用 我是C++新手。两个文件F1和F2之间存在链接器问题。为了更具可读性,我重写了代码和输出

对类的公共方法/变量的未定义引用 我是C++新手。两个文件F1和F2之间存在链接器问题。为了更具可读性,我重写了代码和输出,c++,C++,F1.h: class MYCLASS... public:....// [constructor] etc void myMethod(const string& r); static string s; F1.cpp: void myMethod(const string& r) { MYCLASS::s=r; } [...] void serialize(...) { operation(s,...

F1.h:

class MYCLASS...
   public:....// [constructor] etc         
         void myMethod(const string& r);
         static string s;
F1.cpp:

void myMethod(const string& r)
{
    MYCLASS::s=r;
}
[...]
void serialize(...)
{
   operation(s,...)
}
F2.cpp:

const string& a;
MYCLASS Obj;
Obj.myMethod(a);
目标是在F1.cpp的serialize方法中使用F2.cpp中的字符串a,而不向serialize函数添加任何参数。为此,我尝试使用中间的r变量

编译(基于gcc的编译器)给出错误:

In function `the_function_from_F2.cpp(...)':
F2.cpp:227: undefined reference to `MYCLASS::myMethod(std::basic_string<char,      std::char_traits<char>, std::allocator<char> > const&)'
: In function `myMethod(std::basic_string<char, std::char_traits<char>,   std::allocator<char> > const&)':
F1.cpp:197: undefined reference to `MYCLASS::s'
: In function `MYCLASS::serialize(....) const':
F2.cpp:69: undefined reference to `MYCLASS::s'
在函数'the_function_from_F2.cpp(…)'中:
cpp:227:对“MYCLASS::myMethod(std::basic_string const&)”的未定义引用
:在函数“myMethod(std::basic_string const&)”中:
F1.cpp:197:对“MYCLASS::s”的未定义引用
:在函数“MYCLASS::serialize(..)const”中:
F2.cpp:69:对“MYCLASS::s”的未定义引用
谢谢你的建议

更改为:

void MYCLASS::myMethod(const string& r)
{
    MYCLASS::s=r;
}

std::string MYCLASS::s;
这仍然是一个类方法,因此您需要指定它。

您忘记实际定义
MYCLASS::s
成员。它必须在源文件中完成,如

std::string MYCLASS::s;

您在类中所做的只是声明静态变量。

他们还需要定义
静态
数据成员
s
。谢谢,我添加了它。记住要添加到F2.cpp:std::string MYCLASS::s;我解决了。在.h中,我有带static的声明,在.cpp中,我有不带static的定义。非常感谢。