PDA

View Full Version : How do you do static constants right?



Cruz
5th February 2009, 08:54
I'm just not getting this right somehow. I would like to define a couple of static constants for a class, just like the static final variables in java. This is how I did it:



class SerialCommunication
{
private:
static const qint64 RX_BUFFER_SIZE = 128;
};

void SerialCommunication::receiveMsg()
{
char receiveBuffer[RX_BUFFER_SIZE];
int bytesRead = port->read(receiveBuffer, qMin(port->bytesAvailable(), RX_BUFFER_SIZE));
}


For the second call to RX_BUFFER_SIZE in the read() command I get a compiler error "undefined reference to SerialCommunication::RX_BUFFER_SIZE". How come the first one is ok then? What am I not doing right?

jpn
5th February 2009, 09:09
class SerialCommunication
{
private:
static const qint64 RX_BUFFER_SIZE;
};

const qint64 SerialCommunication::RX_BUFFER_SIZE = 128;

void SerialCommunication::receiveMsg()
{
char receiveBuffer[RX_BUFFER_SIZE];
int bytesRead = port->read(receiveBuffer, qMin(port->bytesAvailable(), RX_BUFFER_SIZE));
}

Cruz
5th February 2009, 09:11
Kinda sucks though that you have to declare and initialize in two different places.

jpn
5th February 2009, 10:53
Or you can just define it outside SerialCommunication in the .cpp file.

Cruz
5th February 2009, 14:37
You mean...global variables that are not members of the class? *scared*

jpn
5th February 2009, 14:47
But if you make it static, it's only visible inside the compilation unit.

caduel
6th February 2009, 07:46
or use an enum:

class SerialCommunication
{
private:
enum { RX_BUFFER_SIZE = 128 };
};

danadam
10th February 2009, 17:35
Kinda sucks though that you have to declare and initialize in two different places.

For integral types you don't have to: in-class initialization of const static data members of integral types (http://www.informit.com/blogs/blog.aspx?uk=30-C-Tips-in-30-Days-Tip-26-in-class-initialization-of-const-static-data-members-of-integral-types). I don't know why your first example didn't work.