简体   繁体   中英

'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

#ifndef RTT_HELLO_HPP
#define RTT_HELLO_HPP

#include<iostream>

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

#endif

Then the class implementation 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.

#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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM