c++visual-studio-2010

C++ a member with an in-class initializer must be const


I am trying to create a static string in my class: (in my header file)

static string description = "foo";

but I'm getting this error:

IntelliSense: a member with an in-class initializer must be const

if I change it to this:

static const string description = "foo";

I get this error instead:

IntelliSense: a member of type "const std::string" cannot have an in-class initializer

What did I do wrong?


Solution

  • What you can do is declare the string in the header and initialize it in your .cpp.

    in MyClass.h

    #include <string>
    class MyClass
    {
      static std::string foo;
    }
    

    in MyClass.cpp

    #include "MyClass.h"
    std::string MyClass::foo = "bar"