开发者

how to define const string in the c++ method

开发者 https://www.devze.com 2023-03-07 02:06 出处:网络
Inside class, I would like to define some const strings.however the compiler reports error when I use

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 defi开发者_Python百科nation?


I think you have to define it outside.

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

const std::string A::s("test");


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";


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.

0

精彩评论

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