加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C inline初始化静态const char *

发布时间:2020-12-16 10:44:13 所属栏目:百科 来源:网络整理
导读:为什么我不能在头文件中初始化静态const char *? 在我的代码中,我在我的类头中: static const char* xml_ID_TAG; 在cpp中: const char* Class::xml_ID_TAG = "id"; xml_ID_TAG变量包含XML文档的属性字符串. 因为它是静态的,const,原始类型(char *)等…我
为什么我不能在头文件中初始化静态const char *?
在我的代码中,我在我的类头中:

static const char* xml_ID_TAG;

在cpp中:

const char* Class::xml_ID_TAG = "id";

xml_ID_TAG变量包含XML文档的属性字符串.
因为它是静态的,const,原始类型(char *)等…我无法弄清楚为什么编译器禁止编写类似的东西:

static const char* xml_ID_TAG = "id";

我正在使用MSVC2013编译器,给出上面的错误示例:“错误:具有类内初始化程序的成员必须是const”

解决方法

一般来说,您必须在一个翻译单元中定义静态成员,并且该语言通过禁止您在周围的类定义中为此类成员编写初始化器来帮助强制执行此操作:

struct T
{
   static int x = 42;
   // ^ error: ISO C++ forbids in-class initialization of
   // non-const static member 'T::x'
};

但是,为方便起见,对常量进行了特殊的例外处理:

struct T
{
   static const int x = 42;
   // ^ OK
};

请注意,在大多数情况下,您仍然需要定义常量(在.cpp文件中将是最佳位置):

const int T::x;

[C++11: 9.4.2/3]:] If a non-volatile const static data member is of integral or enumeration type,its declaration in the class definition can specify a brace-or-equal-initializer in which every initializer-clause that is an assignment-expression is a constant expression (5.19). A static data member of literal type can be declared in the class definition with the constexpr specifier; if so,its declaration shall specify a brace-or-equal-initializer in which every initializer-clause that is an assignment-expression is a constant expression. [ Note: In both these cases,the member may appear in constant expressions. —end note ] The member shall still be defined in a namespace scope if it is odr-used (3.2) in the program and the namespace scope definition shall not contain an initializer.

现在,您的成员不是int,甚至const char * const也不是“整数类型”:

struct T
{
   static const char* const str = "hi";
   // ^ error: 'constexpr' needed for in-class initialization of
   // static data member 'const char* const T::str' of non-integral type
};

但它是一个“字面型”;你的结果是,如果你这样写:

static constexpr const char* const xml_ID_TAG = "id";
//     ^^^^^^^^^             ^^^^^

你应该没问题.无论如何,这可能更有意义:你为什么要改变指针?

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读