Initializing a const member in a class
-
I have a problem initializing a class member that is defined as a constant. My code lookes like this: in header file:
class CMyClass { public: CMyClass(); /* constructor */ struct MyStruct { int field1; const int field2; } stMyStruct; int iVar; ... }
in cpp file:... CMyClass::CMyClass(): stMyStruct.field2(10) { stMyStruct.field1 = 2; iVar = 10; } ...
It gives me a parsing error before "." when I compile. It doesn't seem to recognize stMyStruct. But if I substitute stMyStruct.field2(10) with iVar(10), it compiles fine. jpyp -
I have a problem initializing a class member that is defined as a constant. My code lookes like this: in header file:
class CMyClass { public: CMyClass(); /* constructor */ struct MyStruct { int field1; const int field2; } stMyStruct; int iVar; ... }
in cpp file:... CMyClass::CMyClass(): stMyStruct.field2(10) { stMyStruct.field1 = 2; iVar = 10; } ...
It gives me a parsing error before "." when I compile. It doesn't seem to recognize stMyStruct. But if I substitute stMyStruct.field2(10) with iVar(10), it compiles fine. jpypCMyClass cannot directly initialize a member of a contained class. ( remember structs are a special form of class ) You will need to provide a constructor for the contained class MyStruct that at the very minimum initializes the const member and then have CMyClass constructor use it. Try this...
class CMyClass
{
public:
CMyClass(); /* constructor */struct MyStruct
{
MyStruct( const int f2 ) :
field2( f2 )
{
}int field1; const int field2;
} stMyStruct;
int iVar;
};CMyClass::CMyClass():
stMyStruct(10)
{
stMyStruct.field1 = 2;
iVar = 10;
}Dan
Be clear about the difference between your role as a programmer and as a tester. The tester in you must be suspicious, uncompromising, hostile, and compulsively obsessed with destroying, utterly destroying, the programmer's software. ----- Boris Beizer