How do you do static constants right?
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:
Code:
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?
Re: How do you do static constants right?
Code:
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));
}
Re: How do you do static constants right?
Kinda sucks though that you have to declare and initialize in two different places.
Re: How do you do static constants right?
Or you can just define it outside SerialCommunication in the .cpp file.
Re: How do you do static constants right?
You mean...global variables that are not members of the class? *scared*
Re: How do you do static constants right?
But if you make it static, it's only visible inside the compilation unit.
Re: How do you do static constants right?
or use an enum:
Code:
class SerialCommunication
{
private:
enum { RX_BUFFER_SIZE = 128 };
};
Re: How do you do static constants right?
Quote:
Originally Posted by
Cruz
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. I don't know why your first example didn't work.