Reputation: 336
I need to create a struct inside struct. How to code the constructor correctly? Do I need to create two constructors separately for A and B or can I use only one 'outside' constructor for A like in example below? My attempts resulted in C2597 error.
struct A
{
struct B
{
unsigned n;
int* d;
};
A(unsigned c)
{
B::n = c; // C2597
B::d = new int[c]; // C2597
}
};
Upvotes: 1
Views: 242
Reputation: 14589
You didn't declare a member, in your code B is a nested class of class A.
You have to declare a member of that class.
struct A
{
struct B
{
unsigned n;
int* d;
}; // this is a class-type declaration
B data; // this is member of class A having type of class B
A(unsigned c)
{
data.n = c;
data.d = new int[c];
}
};
Upvotes: 2
Reputation: 2324
You need either to make members of B
static (but in this case you will have one value for whole program or dll in case of Windows):
struct A
{
struct B
{
static unsigned n;
static int* d;
};
A(unsigned c)
{
B::n = c;
B::d = new int[c];
}
};
or create an instance of the B
:
struct A
{
struct B
{
unsigned n;
int* d;
};
A(unsigned c)
{
B b;
b.n = c;
b.d = new int[c];
}
};
If you meant A
to contain B
- that is what you need to do:
struct A
{
struct B
{
unsigned n;
int* d;
} b;
A(unsigned c)
{
b.n = c;
b.d = new int[c];
}
};
Upvotes: 5
Reputation: 234715
You need an instance of B
in order to access the members n
and d
.
struct B
{
unsigned n;
int* d;
} b; // Create an instance of `B`
A(unsigned c)
{
b.n = c;
b.d = new int[c]; // ToDo - you need to release this memory, perhaps in ~B()
}
Either that or make them static
.
Upvotes: 3