Is it possible to declare a string at all in a header (.h) file, in the definition of a Class?
When I want to set a default int
, I do:
class MyClass
{
static const unsigned int kDATA_IMAGE_WIDTH = 1024;
Is there a way to do the same for the string
object?
class MyClass
{
static const string kDEFAULT_FILE_EXTENSION = "png"; // fail
I know I can use #define
...
#define kDEFAULT_FILE_EXTENSION "png"
thanks
edit: added that it is in a class definition. updated examples.
Just like the other data types, to create a string we first declare it, then we can store a value in it. cout << "This is a string." << endl; In order to use the string data type, the C++ string header <string> must be included at the top of the program.
Yes. Although this is not necessarily recommended, it can be easily accomplished with the correct set of macros and a header file. Typically, you should declare variables in C files and create extern definitions for them in header files.
Because a header file might potentially be included by multiple files, it cannot contain definitions that might produce multiple definitions of the same name. The following are not allowed, or are considered very bad practice: built-in type definitions at namespace or global scope.
cstring is the header file required for string functions.
From the error message you gave (emphasis mine):
error: invalid in-class initialization of static data member of non-integral type 'const std::string'
You can do this in a header file, but you cannot do so in a class.
That is:
class MyClass
{
static const std::string invalid = "something";
};
is not valid, but
static const std::string valid = "something else";
is valid.
If you want the static to be a member of the class only, you do this:
//Header
class MyClass
{
static const std::string valid;
};
//Implementation (.cpp) file
const std::string MyClass::valid = "something else again";
Only static const integral class variables may be initialized using the "= constant" syntax.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With