0

Inside class, I would like to define some const strings.however the compiler reports error when I use

class A {
static const std::string s = "test" 
};

inside the class. How to do that? Do I have to define the const outside the class defination?

1
  • As numerous answers have already stated, you must define the value outside the class declaration (typically not in the header file). You can, however, give a value to a built-in type (so sub 'int' for 'std::string' in your example and it will work). Commented May 17, 2011 at 23:48

3 Answers 3

4

I think you have to define it outside.

class A {
  static const std::string s;
};

const std::string A::s("test");
Sign up to request clarification or add additional context in comments.

8 Comments

@Christian , we can define integer const inside, is that right?
but for integer const you could also use enum.
integer constants can be defined inside a class!
@user705414: It is indeed. Static const integral types, including boolean but not including pointer, can be initialized inside the class.
Currently the standard specifies that integral constants can be initialized inside class declaration. Read this for a good explanation why it is so.
|
0

You initialize the static member outside the class (unlike C# where you can declare and initialize a member at the same place).

class A {
static const std::string s;
};

// initialize your static members outside of the class definition.
const std::string A::s = "Some text here";

2 Comments

Not only should they be outside of the class, they should also be (generally speaking) only defined in a .cpp file and not in a .h, or you'll likely violate the [One Definition] Rule(en.wikipedia.org/wiki/One_Definition_Rule).
If I use #pragma once in the header, is that OK?
0

Yes, it should be defined out side the class definition.

const std::string A::s = "test" ;

In C++0x initialization is allowed in the class definition itself (result 1) . But I don't why for std::string type it isn't allowed ( result 2 ).

Ahh .. from the error message it seems it is allowed only for integral data types.

4 Comments

You forgot the A::, as he wants it as a class member.
Christian Rau - Thanks, didn't notice it.
Any compiler supports C++0x standard?
@user - Of my knowledge, C++0x draft isn't released yet. But VS2010, already supports lambda functions.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.