简体   繁体   English

如何在C ++方法中定义const字符串

[英]how to define const string in the c++ method

Inside class, I would like to define some const strings.however the compiler reports error when I use 在类内部,我想定义一些const字符串,但是使用时编译器会报告错误

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? 我是否必须在类定义之外定义const?

I think you have to define it outside. 我认为您必须在外部定义它。

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

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

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 ) . C++0x中,类定义本身( 结果1 )中允许初始化。 But I don't why for std::string type it isn't allowed ( result 2 ). 但是我不为什么不为std::string类型不允许( 结果2 )。

Ahh .. from the error message it seems it is allowed only for integral data types. 从错误消息中,啊..似乎仅允许用于整数数据类型。

You initialize the static member outside the class (unlike C# where you can declare and initialize a member at the same place). 您可以在类外部初始化静态成员(与C#不同,您可以在同一位置声明和初始化成员)。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM