C++简单的编译错误

发布于 2025-01-05 00:57:38 字数 1059 浏览 2 评论 0原文

我遇到编译问题。

  • 我有一个类
  • ,我有一个头文件
  • ,当然还有 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()'

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

I am having a Compile issue.

  • I have one Class
  • I have one header file
  • And of course Main to test my work.

But I am getting compile error, it is out of my understanding what I am doing wrong.

Header File:

#ifndef AGENT_H
#define AGENT_H

using namespace std;

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

#endif  /* AGENT_H */

Agent Class (Agent.cpp)

#include "Agent.h"

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

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

And my Main:

 #include <cstdlib>
 #include <iostream>

#include "Agent.h"
using namespace std;


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

So I am getting such strange error:

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()'

Could you guys help me understand whats wrong there?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

待"谢繁草 2025-01-12 00:57:38

您的头文件中需要有一个#include

另外,为了获得良好的实践,请将 using namespace 保留在 .cpp 文件中(如果有)。

You need an #include <string> in your header file.

Also, for good practice, keep the using namespaces in your .cpp files, if any.

不念旧人 2025-01-12 00:57:38

您在编译时没有告诉编译器有关 Agent.cpp 的信息。也就是说,对于 g++,你需要这样的东西:

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

You compiled without telling the compiler about Agent.cpp. I.e. you need something like this, for g++:

$ g++ main.cpp Agent.cpp -o myprogram
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文