Const in header
-
how to declare a constant in header file? in THINKING IN C++ it is: "extern const NOME;"...
ah, could i initializate the constant in header file? -
For an integer constant I would use
@
enum { CONSTANT = 123 }
@ . For char *:
@
const char * const MY_CONSTANT = "ABC";
@ -
Just remove the extern qualifier and add the initialization:
@const char * NOME = "xxx";@ -
Note though, that there is a difference between
@
const char * NOME = "xxx";
@
and
@
const char * const NOME = "xxx";
@
The first is a pointer with a constant value (i.e the value at the address can't change, but you can change the pointer to point to a different value at another address), the second a constant pointer to constant content (i.e. the pointed to address and the content at that address don't change). The later one is probably what you want. -
ah, so for const QString NOME = "xx"; i must write const char * NOEM = "xx"; ? thank you! =)
-
@const char * const NOEM@
if you want it to be a true constant -
[quote author="spode" date="1312716608"]ah, so for const QString NOME = "xx"; i must write const char * NOEM = "xx"; ? thank you! =)[/quote]
Why don't you just write:
@
const QString NOME = QString("xxx");
@Why deal with that ancient char arrays?
-
It's less overhead overhead when copying and comparing (since the pointer itself is const). Also even with QString you still have "xxx" as a const char* and then you create a unicode representation of it in memory (which is additional overhead). It depends on how often you actually need to display that to the user. If you need it more as an internal constant const char * const is perfectly fine IMO.
-
And you're lost with anything else than 7 bit ASCII; as soon as other QStrings are involved it's probably converted again and again.
Of course there are use cases for plain const char * constants, but IMO they are very limited.
It's for a reason that ever serious C++ framework has its string classes :-)