Define a struct inside a class in C++

后端 未结 6 1093
日久生厌
日久生厌 2020-12-13 03:42

Can someone give me an example about how to define a new type of struct in a class in C++.

Thanks.

6条回答
  •  情歌与酒
    2020-12-13 04:01

    The other answers here have demonstrated how to define structs inside of classes. There’s another way to do this, and that’s to declare the struct inside the class, but define it outside. This can be useful, for example, if the struct is decently complex and likely to be used standalone in a way that would benefit from being described in detail somewhere else.

    The syntax for this is as follows:

    class Container {
    
        ...
    
        struct Inner; // Declare, but not define, the struct.
    
        ...
    
    };
    
    struct Container::Inner {
       /* Define the struct here. */
    };
    

    You more commonly would see this in the context of defining nested classes rather than structs (a common example would be defining an iterator type for a collection class), but I thought for completeness it would be worth showing off here.

提交回复
热议问题