简体   繁体   English

将类分为.h和.cpp文件时出现“未命名类型”错误

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

I have created three simple c++ files as follows: rtt_hello.hpp 我创建了三个简单的c ++文件,如下所示:rtt_hello.hpp

#ifndef RTT_HELLO_HPP
#define RTT_HELLO_HPP

#include<iostream>

class displayer
{
    public:
        void display();
};

#endif

Then the class implementation displayer.cpp 然后该类实现displayer.cpp

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

And finally the main program rtt_hello.cpp.I don't have main because I want to use the object in a different application. 最后是主程序rtt_hello.cpp。我没有main,因为我想在其他应用程序中使用该对象。

#include<iostream>
#include "rtt_hello.hpp"

displayer message1;
message1.display();

Now when I compile this I get the error 现在,当我编译它时,我得到了错误

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();
 ^

I created the headers and also included it,Then why does this this error happen ? 我创建了标头并将其包含在内,然后为什么会发生此错误?

You can't just put random code in a file (outside of any function). 您不能只将随机代码放在文件中(任何函数之外)。 At the top level you can only declare/define stuff. 在顶层,您只能声明/定义内容。 An expression like message1.display() needs to be part of a function. message1.display()这样的表达式需要成为函数的一部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 错误:“参数”未命名类型,.cpp和.h文件可能存在问题 - Error: 'argument' does not name a type, supposed problems with .cpp and .h files 分离.h和.cpp文件时出现问题 - Problem separating .h and .cpp file 将 class 分离为 header (.h) 和源 (.cpp) 文件时出现问题 - Problem with separating a class into header (.h) and source (.cpp) file 分离到.h / .cpp后重新定义类 - Redefinition of Class after Separating to .h/.cpp 为什么在AppCode中将类“移动”到具有相同namespace / name.h的文件会导致空.h而所有类代码都移动到.cpp? - Why “Move” of class to file with same namespace/name.h in AppCode results in empty .h while all class code is moved to .cpp? 使用 main.cpp、node.cpp/.h 和 slist.cpp/.h 构建单链表 (C++) [var SLNode 未命名类型:错误] - Building Singly Linked List (C++), using main.cpp, node.cpp/.h, and slist.cpp/.h [var SLNode does not name a type: error] 将 class 代码分离为 header 和 cpp 文件 - Separating class code into a header and cpp file 将类分为cpp和头文件(C ++) - Separating a class into cpp and header file (C++) 模板文件中的类“未命名类型”错误 - Class 'does not name a type' error in template file 将代码分为.h和.cpp文件时的链接器错误 - Linker Error when separating code into .h and .cpp files
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM