未定义的引用static constexpr char [] [英] Undefined reference to static constexpr char[]

查看:226
本文介绍了未定义的引用static constexpr char []的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的类中有一个 static const char 数组。 GCC抱怨并告诉我应该使用 constexpr ,虽然现在告诉我这是一个未定义的引用。如果我使数组非成员,那么它编译。发生了什么?

I want to have a static const char array in my class. GCC complained and told me I should use constexpr, although now it's telling me it's an undefined reference. If I make the array a non-member then it compiles. What is going on?

// .hpp
struct foo {
  void bar();
  static constexpr char baz[] = "quz";
};

// .cpp
void foo::bar() {
  std::string str(baz); // undefined reference to baz
}


推荐答案

添加到您的cpp文件:

Add to your cpp file:

constexpr char foo::baz[];

原因:您必须提供静态成员的定义作为声明。声明和初始化器进入类定义,但成员定义必须是分开的。

Reason: You have to provide the definition of the static member as well as the declaration. The declaration and the initializer go inside the class definition, but the member definition has to be separate.

这篇关于未定义的引用static constexpr char []的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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