获取"错误LNK2019:未解析的外部符号..."

时间:2014-11-20 09:40:52

标签: c++ initialization semantics

我正在尝试使用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函数中的前两行。我明白为什么它在main函数的前两行抱怨,因为没有名为“name”或“name2”的函数。但是我要做的是在一行中声明和初始化一个对象(我和老Java家伙:p),这在C ++中是否可能?我在网上找不到任何迹象表明这一点。

有趣的是,这段代码或多或少地复制了我的讲师在讲座中执行的一些代码。他当然没有声明任何名为“name”和“name2”的函数。对此有任何合理的解释吗?

但为什么函数funk也会产生此错误?我正在做的就是返回我正在发送的对象的副本。

提前致谢!

编辑:这是完整的错误消息。其中有五个。 “SecondApplication”是我项目的名称。

  

错误1错误LNK2019:未解析的外部符号“public:__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&amp;)”(?? 0Text @@ QAE @ ABV0 @@ Z)在函数“class Text __cdecl funk(class)中引用文本)“(?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&amp;)”(?? 4Text @@ QAEXABV0 @@ Z)在函数_main C:\ Users \ XXX中引用\ 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错误LNK1120:4个未解析的外部C:\ Users \ XXX \ Documents \ Visual Studio 2013 \ Projects \ SecondApplication \ Debug \ SecondApplication.exe 1 1 SecondApplication

1 个答案:

答案 0 :(得分:1)

如果您忘记将“Text.cpp”添加到项目中,那么您将看到链接错误(而不是编译错误),因此它不会被编译和链接。

代码中有两个错误 - 一个在复制构造函数中,一个在赋值运算符中。

由于编译器没有抱怨这两个错误,我怀疑你忘了将文件添加到项目中。