tags:

views:

107

answers:

4

Hi,

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.

+1  A: 

yes, but strings are not intrinsic to C++. you need the proper #include

#include <string>

static const std::string kDEFAULT_FILE_EXTENSION = "png";

On a side note. I've never seen C++ code use the k prefix to denote a constant. I think that's an Objective-C convention. Also, ALL_CAPS symbols should really be reserved for #define macros, not language constants.

Ferruccio
hmmm, thanks, but not working me?... : `error: invalid in-class initialization of static data member of non-integral type 'const std::string'`
Ross
I did not realize you were trying to do this inside a class.
Ferruccio
Appologies... my inexperience, I should have mentioned it.
Ross
@Ferruccio thanks for this extra info, it is great. I am coming from Obj-C to C++.
Ross
A: 

Yes, you should be able to declare strings or put any other sort of code in your header file. It might be failing because the header file is missing the #include which defines string, or you need to put a "std::" in front of it if you aren't "using namespace std" in the header file.

Please update your question with the specific compiler error you're seeing if these suggestions don't fix it. Hopefully this helps.

Kevin D.
+5  A: 

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

static const std::string MyClass::valid = "something else again";

Only static const integral class variables may be initialized using the "= constant" syntax.

Billy ONeal
Sorry, it is within a class definition. I've updated my question. Thanks
Ross
@Ross: Well then my answer doesn't change. ;) The last codebox tells you how to do this correctly.
Billy ONeal
A: 

I don't have the context here, but if the intent is to define an immutable array of characters terminated by a '\0', why not use:

static const char kDEFAULT_FILE_EXTENSION[] = "png";

Also, note that there's no transparent conversion between string class and const char * without invoking string::c_str()..

Atul