PDA

View Full Version : const member definitions in a class ....



TheKedge
14th February 2006, 08:50
Sorry,
I know this question has been asked many a time but what is the "standard" work around for defining a consts (and const arrays) in a C++ class??? That is, is there a nice way of doing it? What's the best and most readable way of doing it?

it's horrible:


class MyClass
{

const int arraySize = 3;//won't work
const int arr[3] = {1, 2, 3}; //won't work

enum{
arraySize = 3;
};
//but I still can't ...
const int arr[arraySize] = {1, 2, 3};

//see, I've got stuff that's really natural in a class definition - rather than implementation
//thus:
enum RANGE {
_OPEN = 0,
_2R,
_20R,
_200R,
_2K,
_20K,
_200K,
_2M
};
const double _RAN[_2M+1] = {
0,
2,
20,
200,
2000,
20000,
200000,
2000000
};
//so that in my code I can say things like setRange(_RAN[_2M]);
}

thanks
Kev

high_flyer
14th February 2006, 09:02
just do:


class MyClass : pulic ParentClass
{
const int arraySize
....
}

MyClass::MyClass():ParentClass(),arraySize(3)

TheKedge
14th February 2006, 09:28
Won't that get messy with a const array as in my example?
K

high_flyer
14th February 2006, 10:02
Oh right, you have a const array too...
Hmm...
I found this (http://groups.google.com/group/alt.comp.lang.learn.c-c++/browse_frm/thread/273f30de80269eb3/61eaff97238475ea?lnk=st&q=initializing+%22const+array%22+in+class&rnum=2&hl=en#61eaff97238475ea) on google.

Weaver
14th February 2006, 12:11
Declare in your class:

static const int arr[];


and in your cpp file:

const int MyClass::arr[] = { 1, 2, 3 };

TheKedge
15th February 2006, 13:03
Ha!
salubrious, dude!
that'll do, nicely.

thanks
K