【发布时间】:2015-01-18 02:45:45
【问题描述】:
我正在尝试开始使用 C++,但我不断收到此错误。我知道我的代码的哪些部分正在生成它,但我认为这些部分中至少有一个不应该生成它们。
我正在创建一个名为Text 的类,它的功能类似于std::string 类,只是为了进行实验并更好地理解值语义。
无论如何,这些是我的文件:
文本.h:
#ifndef TEXT
#define TEXT
class Text {
public:
Text(const char *str);
Text(const Text& other);
void operator=(const Text& other);
~Text();
private:
int size;
char* cptr;
};
#endif
文本.cpp:
#include "Text.h"
#include <cstring>
#include <iostream>
using namespace std;
Text::Text(const char* str) {
size = strlen(str) + 1;
cptr = new char[size];
strcpy(cptr, str);
}
Text::Text(const Text& other) {
size = other.size;
cptr = new char[size];
strcpy(cptr, str);
}
void Text::operator=(const Text& other){
delete [] cptr;
size = other.size;
cptr = new char[size];
strcpy(cptr, other.ctpr);
}
Text::~Text() {
delete [] cptr;
}
Main.cpp:
#include <iostream>
#include "Text.h"
using namespace std;
Text funk(Text t) {
// ...
return t;
}
int main() {
Text name("Mark");
Text name2("Knopfler");
name = funk(name);
name = name2;
return 0;
}
所以导致错误的是函数funk,以及main 函数中的前两行。我明白为什么它在主函数的前两行抱怨,因为没有名为“name”或“name2”的函数。但是我想要做的是在一行中声明和初始化一个对象(我和 Java 的老家伙:p),这在 C++ 中是否可行?我在网上找不到任何表明这一点的东西。
有趣的是,这段代码或多或少是从我的讲师在讲座期间执行得很好的一些代码复制而来的。而且他当然也没有声明任何名为“name”和“name2”的函数。对此有何合理解释?
但是为什么函数funk 也会产生这个错误呢?我所做的只是返回我发送的对象的副本。
提前致谢!
编辑:这里是完整的错误信息。其中有五个。 “SecondApplication”是我的项目名称。
错误 1 错误 LNK2019:函数 _main C:\Users\XXX\Documents\ 中引用的未解析外部符号“public: __thiscall Text::Text(char const *)”(??0Text@@QAE@PBD@Z) Visual Studio 2013\Projects\SecondApplication\SecondApplication.obj SecondApplication
错误 2 错误 LNK2019:无法解析的外部符号“public: __thiscall Text::Text(class Text const &)”(??0Text@@QAE@ABV0@@Z) 在函数“class Text __cdecl funk(class Text )" (?funk@@YA?AVText@@V1@@Z) C:\Users\XXX\Documents\Visual Studio 2013\Projects\SecondApplication\SecondApplication.obj SecondApplication
错误 3 错误 LNK2019:函数 _main C:\Users\XXX\ 中引用的未解析外部符号“public: void __thiscall Text::operator=(class Text const &)”(??4Text@@QAEXABV0@@Z) Documents\Visual Studio 2013\Projects\SecondApplication\SecondApplication.obj SecondApplication
错误 4 错误 LNK2019:未解析的外部符号“public: __thiscall Text::~Text(void)”(??1Text@@QAE@XZ) 在函数“class Text __cdecl funk(class Text)”(?funk) 中引用@@YA?AVText@@V1@@Z) C:\Users\XXX\Documents\Visual Studio 2013\Projects\SecondApplication\SecondApplication.obj SecondApplication
错误 5 error LNK1120: 4 unresolved externals C:\Users\XXX\Documents\Visual Studio 2013\Projects\SecondApplication\Debug\SecondApplication.exe 1 1 SecondApplication
【问题讨论】:
-
name和name2是变量,而不是函数。你在一行中声明和初始化,这在 C++ 中很常见。您应该发布完整的错误消息,而不仅仅是说它们存在。 -
您应该尝试在此站点上搜索“LNK2019”。这个问题每天被问十次左右,原因相同。
-
嗯,有很多。据我所知,它们中的大多数都没有被标记为已回答。我在stackoverflow上尝试了关于该主题的前30个线程中建议的解决方案,但遗憾的是,它们都没有奏效。我的代码没有问题吗?另外,在旁注中。似乎这个错误可能是由一堆不同的事情引起的。一种模式是人们使用静态变量,但我没有。一个是人们忘记定义在头文件中声明的函数。但我也没有这样做。
-
就是这样。谢谢!
-
是否可以将评论标记为该问题的答案?或者我如何将此问题标记为已回答?
标签: c++ initialization semantics