C ++静态常量字符串(类成员) [英] C++ static constant string (class member)

查看:142
本文介绍了C ++静态常量字符串(类成员)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想有一个类的私有静态常量(在这种情况下是一个形状工厂)。
我想有类似的东西。

I'd like to have a private static constant for a class (in this case a shape-factory). I'd like to have something of the sort.

class A {
   private:
      static const string RECTANGLE = "rectangle";
}


$ b as:

Unfortunately I get all sorts of error from the C++ (g++) compiler, such as:


ISO C ++禁止初始化
成员'RECTANGLE'

ISO C++ forbids initialization of member ‘RECTANGLE’

非整数类型'std :: string'的静态数据成员的无效类初始化

invalid in-class initialization of static data member of non-integral type ‘std::string’

错误:使'RECTANGLE'静态

error: making ‘RECTANGLE’ static

这告诉我这种成员设计不符合标准。如何在不使用#define指令(我想避免数据全局性的丑陋)的情况下有一个私有文字常量(或者可能是public)。

This tells me that this sort of member design is not compliant with the standard. How do you have a private literal constant (or perhaps public) without having to use a #define directive (I want to avoid the uglyness of data globality!)

任何帮助谢谢。感谢。

推荐答案

您必须在类定义之外定义静态成员,并在那里提供初始值。

You have to define your static member outside the class definition and provide the initializer there.

首先

// In a header file (if it is in a header file in your case)
class A {   
private:      
  static const string RECTANGLE;
};

,然后

// In one of the implementation files
const string A::RECTANGLE = "rectangle";

您最初尝试使用的语法(类定义中的初始化器)仅允许使用整数和枚举类型。

The syntax you were originally trying to use (initializer inside class definition) is only allowed with integral and enum types.

这篇关于C ++静态常量字符串(类成员)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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