structures, inheritance and definition
i need to help with structures, inheritance and definition.
//define struct
struct tStruct1{
int a;
};
//definition
tStruct1 struct1{1};
and inheritance
struct tStruct2:tStruct1{
int b;
};
How can I define it in declaration line?
tStruct2 struct2{ ????? };
One more question, how can i use inheritance for structur开发者_如何学Goes defined with typedef struct?
First off, the typedef
for a structure doesn't change anything, it only introduces an alternative name for the type. You can still inherit from it as usual.
The Type identifier{params}
syntax for definitions is C++0x syntax for the new uniform initialization. In pre-C++0x you have two choices for initialization of user-defined types.
Aggregate Initialization
Aggregates are POD types and arrays of PODs or built-in types. They can be initialized using initializer lists with curly braces:
struct A {
int i;
};
struct B {
A j;
int k;
};
B b = {{1}, 2 };
This is covered in more detail in this InformIT article.
As noted this only works for POD-types and thus doesn't work when inheritance comes into play. In that case you have to use
User-defined constructors
They allow you to initialize your custom types rather freely by defining special member functions:
struct A {
int i;
A(int number) : i(number) {}
};
struct B : A {
int j;
B(int number1, number2) : A(number1), j(number2) {}
};
B b(1, 2);
Constructors are covered in more detail in this InformIT article.
精彩评论