gpt4 book ai didi

c++ - 对类的公共(public)方法/变量的 undefined reference

转载 作者:行者123 更新时间:2023-11-28 03:06:55 25 4
gpt4 key购买 nike

我是 C++ 新手。我在 2 个文件 F1 和 F2 之间存在链接器问题。为了更具可读性,我重写了代码和输出。

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 的序列化方法中使用 F2.cpp 中的字符串 a,而不向序列化函数添加任何参数。为此,我正在尝试使用中间 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'

感谢您的任何建议!

最佳答案

更改为:

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

std::string MYCLASS::s;

这仍然是一个类方法,因此您需要指定它。

关于c++ - 对类的公共(public)方法/变量的 undefined reference ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19450156/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com