简体   繁体   中英

struct as a type for function in C++

I am learning C++ and am trying to create a function with a return type of "my_message_t" that was defined in the class definition. However when I tried to compile it, compiler informed me that error: 'my_message_t' does not name a type

I have the following code (protocols.h and protocols.cpp)

    namespace Protocols {
                class Messages {
                    public:

                        typedef struct _my_message_t {
                            //stuffs
                        } my_message_t;

                        typedef enum {
                                //stuffs 
                        } my_message_e;

                private:
                    my_message_t                            my_msg;
                    my_message_e                            msg_en; 

                public:
                    Messages();     
                    ~Messages();    

                    my_message_t create_message(const my_message__e); 

            };
        };

with the class definition is below:

            namespace Protocols {

                    Messages::Messages(){
                        //stuff
                    };

                    Messages::~Messages(){
                        //stuffs
                    }

                    my_message_t Messages::create_message(my_message_e type){
                        my_message_t msg;

                        //do stuffs

                        return msg;
                    }
            }

Why I can not create a function with a type of my_message_t ? How do I fix that code above?

my_message_t is scoped inside the Messages class, so it needs to be qualified when used outside a member of the class:

Messages::my_message_t Messages::create_message(my_message_e type){
^^^^^^^^^^
    // do stuffs
}

Note that you don't need that in the function parameter list, only the return type; a quirk of the language means that the parameter list is scoped inside the function, and the return type outside.

Change:

my_message_t Messages::create_message(my_message_type_e type)

to:

Messages::my_message_t Messages::create_message(my_message_e type)
^^^^^^^^^^

my_message_t是在Messages类内部定义的类型,因此您需要:

Messages::my_message_t Messages::create_message(my_message_type_e type)

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