包括c++中的头文件(类定义和方法实现)

Including header files in C++ (class definition and method implementation)

本文关键字:定义 方法 实现 c++ 文件 包括      更新时间:2023-10-16

我已经检查了StackOverflow以找到解决我的问题的方法,但我想我可能错过了一些东西。我试图在头文件(.h)中定义一个类,并在cpp文件(.cpp)中实现其方法,但它不起作用。

main.cpp:

#include <iostream>
#include "Message.h"
using namespace std;
int main()
{
    Message *t = new (Message);
    t->display();
    return 0;
}

message:

#ifndef MESSAGE_H_INCLUDED
#define MESSAGE_H_INCLUDED
class Message {
public:
    void display();
};
#endif // MESSAGE_H_INCLUDED

Message.cpp:

#include "Message.h"
void Message::display() {
    cout << "Hello!";
}

我不明白为什么我一直得到以下错误

undefined reference to 'Message::display()'

g++ -std=c++11 Message.cpp main.cpp

命令编译该文件