【问题标题】:I'm trying to declare a constant string in my C++ class, but I get an "Invalid in-class assignment", and I don't understand why我试图在我的 C++ 类中声明一个常量字符串,但我得到一个“无效的课堂分配”,我不明白为什么
【发布时间】:2011-05-16 08:45:50
【问题描述】:

代码如下:

#include <string>

class Config {
public:
    static const std::string asdf = "hello world!";
}

我无法诊断为什么这不起作用

【问题讨论】:

  • 感谢所有非常快速的回复。

标签: c++


【解决方案1】:

类中只能初始化整型(假设它们被声明为static const)。

这样做:

//Config.h
class Config 
{
public:
    static const std::string asdf; //declaration
    static const int demo_integral = 100; //initialization is allowed!
}

//Config.cpp 
const std::string Config::asdf = "hello world!"; //definition & initialization 
const int Config::demo_integral; //already initialized in the class!

定义应该在.cpp文件中,否则如果你在头文件本身中定义它们,然后你将头文件包含在多个文件中,你会得到多个定义错误!

【讨论】:

  • 作为一个附带问题,我使用 eclipse 并且它已经添加了一个 #IFNDEF 预处理器指令,那么我放置头文件是否可以接受?
  • @anonymous:在这种情况下,是的。 :-)
  • 哦,最后一个问题。我刚刚意识到使用一个类对我来说似乎是不合适的,因为 config.h 的整个点是一个带有一堆常量的配置头。我更适合使用#define 还是应该创建一个结构?抱歉,我对来自 Java 的 C++ 很陌生。
  • @anonymous:视情况而定。配置在这里可能意味着很多事情。它是对程序或某些组件的初始化阶段的某种输入,您希望即使在部署之后也可以像在生产环境中那样对其进行配置?如果是这种情况,那么您应该使用一些xml 配置,以便在生产中可以根据需要进行更改。或者,如果您希望您的程序在编译/构建之前可配置,那么在这种情况下您也可以使用常量。但是#define 在 C++ 中并不是一个好主意。你有更好的选择。使用enum 或const 数据类型!
  • @anonynous Nawaz 在他的回答中涵盖了您需要的所有内容。注意指示哪个部分进入哪个文件的 cmets。我怀疑你的教授对好的设计更感兴趣,而不仅仅是正确性。
【解决方案2】:

你不能这样做。

因为它是静态的,所以它必须在类外定义(类内的const std::string asdf 只是声明,因为static)

在你的情况下:

const std::string Config::asdf = "hello world!"

你应该在构造函数中初始化所有数据成员,而不是这样:

class A
{
    var_t var = value;
};

【讨论】:

    【解决方案3】:

    除了整型之外,静态 const 成员不能在类定义范围内初始化。你必须拆分它,如下所示。

    在头文件中:

    #include <string>
    
    class Config {
    public:
        static const std::string asdf;
    };
    

    在 .cpp 文件中

    const std::string Config::asdf = "hello world!";
    

    【讨论】:

      【解决方案4】:

      你必须在类之外声明它:

      #include <string>
      
      class Config {
      public:
          static const std::string asdf = "hello world!";
      }
      
      const std::string Config::asdf = "hello world";
      

      也看here。

      【讨论】:

        【解决方案5】:

        发件人:

        http://cplusplus.syntaxerrors.info/index.php?title=Invalid_in-class_initialization_of_static_data_member_of_non-integral_type_%E2%80%98const_char*%E2%80%99

        您只能首先在类定义中分配枚举类型或“整数”类型(int、char、long 等)的变量。 Char* 不是整数类型,所以只能在全局范围内赋值。

        您可以这样做作为一种解决方法:

        #include <string>
        
        class Config {
        public:
            static const std::string asdf()
            {
               return "Hello World!";
            }
        };
        

        【讨论】:

          猜你喜欢
          • 2013-11-06
          • 2012-05-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-07-23
          相关资源
          最近更新 更多