将类分成 .h 和 .cpp 文件时'Does not name a type'错误

'Does not name a type' error while separating class into a .h and .cpp file

本文关键字:Does not name 错误 type 文件 cpp      更新时间:2023-10-16

我创建了三个简单的 c++ 文件,如下所示:rtt_hello.hpp

#ifndef RTT_HELLO_HPP
#define RTT_HELLO_HPP
#include<iostream>
class displayer
{
    public:
        void display();
};
#endif

然后是类实现显示器.cpp

#include <iostream>
#include "rtt_hello.hpp"
void displayer::display()
{
    std::cout<<"Hello";
}

最后是主程序rtt_hello.cpp.我没有主程序,因为我想在不同的应用程序中使用该对象。

#include<iostream>
#include "rtt_hello.hpp"
displayer message1;
message1.display();

现在当我编译它时,我收到错误

sambeet@Holmes ~/NewRockPort/x86/Build/rock/rtt_test $ /home/sambeet/NewRockPort/x86/Install/rtems/4.11.0-rc3/bin/i386-rtems4.11-g++ rtt_hello.cpp displayer.cpp -Ihome/sambeet/NewRockPort/x86/Build/rock/rtt_test/ 
rtt_hello.cpp:5:1: error: 'message1' does not name a type
 message1.display();
 ^

我创建了标头并包含它,那么为什么会发生此错误呢?

你不能只把随机代码放在一个文件中(在任何函数之外)。在顶层,您只能声明/定义内容。像message1.display()这样的表达式需要成为函数的一部分。