Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define a struct inside a class in C++

Tags:

c++

class

struct

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

Thanks.

like image 670
small_potato Avatar asked Mar 30 '10 06:03

small_potato


People also ask

Can I define a struct inside a class?

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.

Can you define a struct inside a function in C?

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 { /* ...

Can we write struct inside main?

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.


2 Answers

Something like this:

class Class {     // visibility will default to private unless you specify it     struct Struct {         //specify members here;     }; }; 
like image 148
sharptooth Avatar answered Oct 15 '22 03:10

sharptooth


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.

like image 27
Afriza N. Arief Avatar answered Oct 15 '22 03:10

Afriza N. Arief