mlimber a écrit :[color=blue]
> Vince wrote:
>[color=green]
>>I recently learned that it's possible to put a constructor inside a struct.[/color]
>
>
> Correct. structs differ from classes only in that their default is
> public rather than private access.
>
>[color=green]
>>My question is : Is it possible to do the following :
>>
>>typedef struct _TRecInfo
>>{
>>_TRecInfo(int nKey, int nMode): nKey(nKey), nMode(nMode){}; //constructor
>>
>>int nKey;
>>int nMode;
>>} TRecInfo;[/color]
>
>
> Yes, but more common notation would be:
>
> struct TRecInfo
> {
> TRecInfo( int nKey, int nMode )
> : nKey_(nKey), nMode_(nMode)
> {} // no semicolon necessary
>
> int nKey_;
> int nMode_;
> };
>
> You might even make the data private and provide accessor methods,
> depending on what the class does. Anyway, the typedef is superfluous
> because in C++ you can still refer to that struct as simply "TRecInfo"
> (no "struct" keyword necessary).
>
>[color=green]
>>and after something like :
>>
>>TRecInfo recInfo[255];
>>recInfo[0x17] = new TRecInfo(0x0E, 1);[/color]
>
>
> Presumably you meant someting like:
>
> TRecInfo* records[ 255 ];
> records[ 0x17 ] = new TRecInfo( 0xe, 1 );
>
> The syntax you used would not work because the first line would call an
> implicit default constructor for each element in the array (and you'd
> get an error because TRecInfo::TRecInfo(void) doesn't exist) and
> because the second line would be unable to find a conversion from
> TRecInfo (the left-hand side) to TRecInfo* (the right-hand side).
>
> If you want an array of these, consider using std::vector instead of
> manually allocating an array yourself:
>
> #include <vector>
>
> // ...
>
> void Foo()
> {
> std::vector<TRecInfo> records( 255, TRecInfo(0,0) );
> // ...
> }
>
> For more on constructors, see these FAQs:
>
>
http://www.parashift.com/c++-faq-lite/ctors.html
>
> Cheers! --M
>[/color]
Do I need to call delete after ?
Because I am initializing this struct array in my constructor.
CCardReader::CCardReader()
{
recInfo[0x17] = new TRecInfo(0x0E, 1);
recInfo[0x18] = new TRecInfo(0x12, 1);
...
}
CCardReader::~CCardReader()
{
???
}