使用头文件和实现文件实例化和使用 c++ class

Instantiating & using c++ class using header & implementation files

我基本上是在尝试从 c++ 中的 class 实例化一个对象并使用其中一个成员函数。这感觉像是一个非常标准的问题,但我在网上找到的所有解决方案要么是简单的括号问题,要么是看起来非常明显的范围解析问题,要么是大量复杂的示例,这些示例掩盖了实际发生的事情过于复杂。我真的很感谢任何能够帮助我理解我在处理这些文件时做错了什么的人。

我得到的错误是

undefined reference to Test::Test()'

undefined reference to Test::msg()'

我有三个文件,一个主文件,一个Test.hpp,和Test.cpp。

main.cpp

#include "Test.hpp"
#include <iostream>
using namespace std;

int main(){

    Test var;
    var.msg();

    return 0;
}

Test.hpp

#ifndef TEST_HPP
#define TEST_HPP

class Test{
public:
    Test();
    void msg();
};
#endif

Test.cpp

#include "Test.hpp"
#include <iostream>
using namespace std;

Test::Test(){
    cout << "instantiated\n\n";
}
void Test::msg(){
    cout << "Hello\n\n";
}

缺点ide你使用代码块作为你的 IDE 只需转到:项目设置 -> 项目构建选项 -> 搜索目录 -> 添加并找到你的 .cpp 和 .h 文件的位置是。然后它会询问您是否要将其保留为相对路径。说不。

如果您使用其他 ide 它几乎相同的过程,只需评论我,我会向您提供 ide 步骤。

顺便说一下,没有必要在 main 中包含 iostream,因为您已经在测试中包含了它。