Const in header
-
wrote on 7 Aug 2011, 10:09 last edited by
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? -
wrote on 7 Aug 2011, 11:01 last edited by
For an integer constant I would use
@
enum { CONSTANT = 123 }
@ . For char *:
@
const char * const MY_CONSTANT = "ABC";
@ -
wrote on 7 Aug 2011, 11:06 last edited by
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. -
wrote on 7 Aug 2011, 11:30 last edited by
ah, so for const QString NOME = "xx"; i must write const char * NOEM = "xx"; ? thank you! =)
-
wrote on 7 Aug 2011, 11:47 last edited by
[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?
-
wrote on 7 Aug 2011, 12:04 last edited by
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.
-
wrote on 7 Aug 2011, 14:46 last edited by
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 :-)
9/9