我正在尝试开始使用C ++,但我一直收到此错误。我知道我的代码的哪些部分正在生成它,但是我认为这些部分中至少有一部分不应该生成它们。
我正在创建一个称为类的类,该类Text
的工作方式与std::string
该类相似,只是为了实验并更好地理解值语义。
无论如何,这些是我的文件:
Text.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
Text.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:未解析的外部符号“公共:__thiscall Text :: Text(char const *)”(?? 0Text @@ QAE @ PBD @ Z)在函数_main C:\ Users \ XXX \ Documents \ 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:未解析的外部符号“ public:void __thiscall Text :: operator =(class Text const&)”(?? 4Text @@ QAEXABV0 @@ Z)在函数_main C:\ Users \ XXX \ Documents \ Visual中引用Studio 2013 \ Projects \ SecondApplication \ SecondApplication.obj SecondApplication
错误4错误LNK2019:未解析的外部符号“公共:__thiscall Text ::〜Text(void)”(?? 1Text @@ QAE @ XZ)在函数“类Text __cdecl funk(类Text)”中引用(?funk @@ YA) AVText @@ V1 @@ Z)C:\ Users \ XXX \ Documents \ Visual Studio 2013 \ Projects \ SecondApplication \ SecondApplication.obj SecondApplication
错误5错误LNK1120:4个未解析的外部C:\ Users \ XXX \ Documents \ Visual Studio 2013 \ Projects \ SecondApplication \ Debug \ SecondApplication.exe 1 1 SecondApplication
例如,如果忘记将“ Text.cpp”添加到项目中,则不会得到编译和链接,则将看到链接错误(不是编译错误)。
代码中有两个错误-一个在复制构造函数中,一个在赋值运算符中。
由于编译器没有抱怨这两个错误,因此我怀疑您忘记了将文件添加到项目中。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句