【问题标题】:C++ a member with an in-class initializer must be constC++ 具有类内初始化程序的成员必须是 const
【发布时间】:2012-11-07 17:22:33
【问题描述】:

我正在尝试在我的类中创建一个静态字符串:(在我的头文件中)

static string description = "foo";

但我收到此错误:

IntelliSense: a member with an in-class initializer must be const

如果我把它改成这样:

static const string description = "foo";

我得到了这个错误:

IntelliSense: a member of type "const std::string" cannot have an in-class initializer

我做错了什么?

【问题讨论】:

  • 使用描述变量粘贴代码

标签: c++ visual-studio-2010


【解决方案1】:

您可以做的是在标头中声明字符串并在您的 .cpp 中对其进行初始化。

在 MyClass.h 中

#include <string>
class MyClass
{
  static std::string foo;
}

在 MyClass.cpp 中

#include "MyClass.h"
std::string MyClass::foo = "bar"

【讨论】:

【解决方案2】:

忽略特定的错误消息,核心问题是您试图在声明中初始化静态成员属性,而通常应该在定义中完成。

// header
struct test {
  static std::string x;
};
// single cpp
std::string test::x = "foo";

现在回到错误消息。在 C++03 标准中有一个例外,它允许为常量整数类型的声明提供初始化程序,以便该值可以在包含标头的所有翻译单元中可见,因此可以用作常量表达式:

// header
struct test {
   static const int size = 10;
};
// some translation unit can do
struct A {
   int array[test::size];
};

如果值是在变量定义中定义的,那么编译器只能在该单个翻译单元中使用它。似乎您的编译器正在执行两项测试,一项针对 const-ness,一项针对 integral 部分,因此有两条错误消息。

另一个可能影响编译器设计的事情是 C++11 标准允许在类的非静态成员的声明中使用初始化器,然后将在每个构造函数的初始化器列表中使用它不为该字段提供值:

struct test {
   int a = 10;
   int b = 5;
   test() : a(5) // b(5) implicitly generated
   {} 
};

这与您的特定问题无关,因为您的成员是静态的,但它可能解释了为什么编译器中的测试按原样拆分。

【讨论】:

  • 你有什么只有头文件的库?
  • @ShitalShah:如果你有一个 C++17 编译器(gcc 刚刚推出),你可以使用内联变量,但适用于所有版本的简单答案是你将变量推送为一个局部静态变量:struct T { static const std::string&amp; x() { static std::string x = "foo"; return x; } };
【解决方案3】:

将声明与定义分开。在头文件中,这样做:

static string description;

然后在一个翻译单元(一个 CPP 文件)中,执行以下操作:

string type::description = "foo";

【讨论】:

    【解决方案4】:

    我不知道静态成员和常量成员之间究竟需要什么。静态成员将与类本身相关联,而不是与实例相关联,而常量成员与实例相关联并且是常量。

    但是,这可能与 this 重复

    问候

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-04
      相关资源
      最近更新 更多