如何在头文件中声明静态const char *? [英] How to declare a static const char* in your header file?

查看:333
本文介绍了如何在头文件中声明静态const char *?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的头文件中定义一个常量char *供我的.cpp文件使用。因此,我尝试了以下方法:

I'd like to define a constant char* in my header file for my .cpp file to use. So I've tried this:

private:
    static const char *SOMETHING = "sommething";

这给我带来了以下编译器错误:

Which brings me with the following compiler error:


错误C2864:'SomeClass :: SOMETHING':
只有静态const整型数据
成员才能在
类中初始化

error C2864: 'SomeClass::SOMETHING' : only static const integral data members can be initialized within a class

我是C ++的新手。这里发生了什么?为什么这是非法的?以及如何选择呢?

I'm new to C++. What is going on here? Why is this illegal? And how can you do it alternatively?

推荐答案

除非它们是整数类型,否则您需要在翻译单元中定义静态变量。 。

You need to define static variables in a translation unit, unless they are of integral types.

在标题中:

private:
    static const char *SOMETHING;
    static const int MyInt = 8; // would be ok

在.cpp文件中:

const char *YourClass::SOMETHING = "something";

C ++标准,9.4.2 / 4:

C++ standard, 9.4.2/4:


如果静态数据成员是const
整数或const枚举类型,则
在其
类定义中的声明可以指定
常量-initializer,应为
整数常量表达式。在那种
的情况下,成员可以出现在
范围内的
整数常量表达式中。如果程序中使用的是
,则该成员仍应是在命名空间范围内定义的
,并且命名空间
范围定义不应包含
初始化程序。

If a static data member is of const integral or const enumeration type, its declaration in the class definition can specify a constant-initializer which shall be an integral constant expression. In that case, the member can appear in integral constant expressions within its scope. The member shall still be defined in a namespace scope if it is used in the program and the namespace scope definition shall not contain an initializer.

这篇关于如何在头文件中声明静态const char *?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆