Can someone give me an example about how to define a new type of struct in a class in C++.
Thanks.
Yes you can. In c++, class and struct are kind of similar. We can define not only structure inside a class, but also a class inside one. It is called inner class.
Yes, the standard allows this, and yes, the name you create this way is only visible inside the function (i.e., it has local scope, just like when you define int i; , i has local scope). or, if you're really only going to use it once, struct { /* ...
You don't need to use typedef in order to define a new structured type. This is perfectly valid: struct student_s { char* name; int age; struct student_s* next; }; // Remove "student". Now you don't have a global variable.
Something like this:
class Class { // visibility will default to private unless you specify it struct Struct { //specify members 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With