【问题标题】:C++ Simple compile errorC++ 简单编译错误
【发布时间】:2012-02-12 19:06:53
【问题描述】:

我遇到了编译问题。

  • 我有一个班级
  • 我有一个头文件
  • 当然还有 Main 来测试我的工作。

但是我得到了编译错误,这超出了我的理解,我做错了什么。

头文件:

#ifndef AGENT_H
#define AGENT_H

using namespace std;

class Agent
{
public:
    Agent(string);
    virtual ~Agent();
    private:
    string name;
};

#endif  /* AGENT_H */

代理类(Agent.cpp)

#include "Agent.h"

using namespace std;
Agent::Agent(string _name)
{
   this->name = _name;
}

Agent::~Agent()
{
    delete this->name;
}

还有我的主要:

 #include <cstdlib>
 #include <iostream>

#include "Agent.h"
using namespace std;


int main(int argc, char** argv) 
{
    Agent agent1("Danila"); 
    return 0;
}

所以我收到了这么奇怪的错误:

undefined reference to `Agent::Agent(std::basic_string<char, std::char_traits<char>, std::allocator<char> >)'
/main.cpp:17: undefined reference to `Agent::~Agent()'
/main.cpp:17: undefined reference to `Agent::~Agent()'

你们能帮我理解那里有什么问题吗?

【问题讨论】:

  • 这不是编译器错误。这是一个链接器错误。您的最终链接器调用必须缺少所需的目标文件之一。
  • 这不是编译器错误,肯定不是“奇怪”,这与C无关。
  • main 没有 17 行。你能重新编译或显示你使用的真实代码吗?
  • 不相关:因为name 没有分配给new,所以你不需要delete 它。 Agent 的析构函数应该是空的。
  • 你不能删除这个->名字。它不是指针。

标签: c++ compilation header


【解决方案1】:

您的头文件中需要一个#include &lt;string&gt;

此外,作为一种良好做法,请将 using namespaces 保留在您的 .cpp 文件中(如果有)。

【讨论】:

  • 或者更好,根本不要使用using namespace
  • 同样的错误,它说未定义引用 `Agent::Agent(std::basic_string, std::allocator >)' 在线代理agent1("达尼拉");
  • 在这种情况下,可能是因为您的代理没有链接到生成的可执行文件中(就像其他答案之一所说)。这也可能是它没有在 Agent 中捕获错误的原因。您必须查看配置选项。 Agent.h/cpp 是同一个 Netbeans 项目的一部分吗?它们是否被标记为包含在构建中?不幸的是,我没有将 Netbeans 用于 C++,但我正在尝试在这里应用我对 Visual Studio 的了解。
【解决方案2】:

你编译时没有告诉编译器Agent.cpp。 IE。对于 g++,你需要这样的东西:

$ g++ main.cpp Agent.cpp -o myprogram

【讨论】:

  • 我正在使用 NetBeans,可以在那里做吗?
  • @WildGoat 我的猜测——根据其他 IDE 的经验,为了顺利编译,您必须通过“添加文件”菜单选项或类似的方式添加文件。否则,IDE 不知道 Agent.cpp 并且不会将其放入它生成的 Makefile 中。或者,可能有一个可以直接编辑的项目文件——它将有一个“源”部分。作为最后的手段,您应该能够手动编辑它直接生成的编译器命令,但我怀疑这应该是必要的。
  • 我添加它认为 Netbeans 作为添加新类,但正如我在 Makefile 中看到的那样,没有任何改变,我应该在 makefile 中添加什么以使其正常工作...
  • @WildGoat Add New Class 听起来正是您应该使用的。你试过重新编译吗?在那之前可能不会重新生成 Makefile。如果 Makefile 是自动生成的,请不要编辑它。
  • @WildGoat 嗯,我现在几乎没有技巧了——是否有一些命令可以在不编译的情况下重新制作 Makefile?如果您曾经使用过 Qt,请喜欢 qmake
猜你喜欢
  • 1970-01-01
  • 2015-05-24
  • 2019-05-10
  • 2020-11-20
  • 2022-11-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多