enum initialization issue
Here is a sample program :
class BASE
{
public:
enum ABC
{
ZERO,
开发者_Python百科 ONE,
TWO,
LAST
};
BASE(ABC exp): type(exp)
{
A[ZERO] = "1111";
A[ONE] = "22222";
A[LAST] = "LLLL";
}
virtual const char* what()throw()
{
return A[type];
}
private:
const char* A[LAST];
const ABC type;
};
int main()
{
BASE a(BASE::ONE);
cout<<a.what()<<"\n";
return 0;
}
The above program terminates with segmentation fault, as 'type' enum variable is not initialized with specified value but with some random default ?
A is an array of three pointers, A[0], A[1], and A[2].
You have a pointer to "LLLL" which is OK. But when you try to assign that pointer to A[3], there is no such object as A[3].
You declare the array A
as
const char* A[LAST];
This means that the indices 0 .. (LAST-1)
are all valid. However, in the BASE
constructor you perform
A[LAST] = "LLLL";
This is an out-of-bounds access to the array.
If you want a "LAST" entry, try this:
enum ABC
{
ZERO,
ONE,
TWO,
LAST = TWO
};
精彩评论