开发者

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

This question already has answers here: Static constant string (class member) (11 answers) Closed 1 year ago.

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 MyC开发者_开发百科lass
 {
      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.


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.


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.


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.


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()..


Two choices:

Define a function in the header that is static and returns the string you want.

static std::string kDEFAULT_FILE_EXTENSION()
    {
        return "png";
    }

A macro will do the right thing here

#define STATIC_STRING_IN_HEADER(name,value) static std::string name(){return value;}
STATIC_STRING_IN_HEADER(kDEFAULT_FILE_EXTENSION,"png")
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜