Undefined reference to static constexpr char[](对静态 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.
这篇关于对静态 constexpr char[] 的未定义引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:对静态 constexpr char[] 的未定义引用
基础教程推荐
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 常量变量在标题中不起作用 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 这个宏可以转换成函数吗? 2022-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
