Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I declare a string in a header file in a definition of a class? [duplicate]

Tags:

c++

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.

like image 305
Ross Avatar asked Sep 16 '10 00:09

Ross


People also ask

How do you declare a string header in C++?

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.

Can you declare variables in a header file?

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.

Can header files have definitions?

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.

What is the header file for the string class?

cstring is the header file required for string functions.


1 Answers

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.

like image 177
Billy ONeal Avatar answered Oct 04 '22 18:10

Billy ONeal