member object constructor and enum
Why does this not compile?
File.hpp
class CTest
{
public:
enum enumTest { EN_TEST };
//constructor:
CTest(enumTest f_en);
};
AnotherFile.hpp
#include "File.hpp"
class CAnotherTest
{
public:
CTest obj_Test(CTest::EN_TEST);
};
Visual Studio says: error C2061: syntax error : identifier 'EN_TEST'
armcc compiler says: error: #757: constant "CTest::EN_TEST" is not a type name
Tha开发者_高级运维nks, Mirco
Because,
CTest obj_Test(CTest::EN_TEST);
is evaluated as a function named obj_Test
. Now it should have argument as a type, however, CTest::EN_TEST
is a value, not a type.
If it's intended that obj_Test
an object then you have pass CTest::EN_TEST
to it in the constructor:
class CAnotherTest
{
public:
CAnotherTest () : obj_Test(CTest::EN_TEST) {}
};
Because your syntax for CAnotherTest
is wrong. Perhaps you mean something like this?
class CAnotherTest
{
public:
// Constructor vvv Initialise member variable
CAnotherTest() : obj_Test(CTest::EN_TEST) {}
// Member variable
CTest obj_Test;
};
You cannot initialize like that. In-class initialization can be done for only static const
integral type.
Use initialization-list in the constructor, as:
class CAnotherTest
{
public:
CTest obj_Test; //member declaration. no initialization here
static const int value = 100; //OK. static const integral type!
CAnotherTest() : obj_Test(CTest::EN_TEST) {}
//^^^^^^^^^^^^^^^^^^^^^^^^^^ its called initialization-list
};
const int CAnotherTest::value; //definition goes to .cpp file
精彩评论