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.
declare class & nested struct probably in some header file
class C {
// struct will be private without `public:` keyword
struct S {
// members will be public without `private:` keyword
int sa;
void func();
};
void func(S s);
};
if you want to separate the implementation/definition, maybe in some CPP file
void C::func(S s) {
// implementation here
}
void C::S::func() { // <= note that you need the `full path` to the function
// implementation here
}
if you want to inline the implementation, other answers will do fine.
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:
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.
declare class & nested struct probably in some header file
if you want to separate the implementation/definition, maybe in some CPP file
if you want to inline the implementation, other answers will do fine.
Something like this:
Something like: