这是对未定义的静态constexpr char [] []的引用的后续问题.
以下程序构建并运行良好.
#include <iostream>
struct A {
constexpr static char dict[] = "test";
void print() {
std::cout << A::dict[0] << std::endl;
}
};
int main() {
A a;
a.print();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
但是,如果我A::print()改为:
void print() {
std::cout << A::dict << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
我在g ++ 4.8.2中收到以下链接器错误.
/tmp/cczmF84A.o: In function `A::print()': socc.cc:(.text._ZN1A5printEv[_ZN1A5printEv]+0xd): undefined reference to `A::dict' collect2: error: ld returned 1 exit status
可以通过添加一行来解决链接器错误:
constexpr char A::dict[];
Run Code Online (Sandbox Code Playgroud)
在课堂定义之外.
但是,我不清楚为什么使用数组的一个成员在使用数组时不会导致链接器错误导致链接器错误.
以下程序给出了链接时错误:
#include <iostream>
struct Test { static constexpr char text[] = "Text"; };
int main()
{
std::cout << Test::text << std::endl; // error: undefined reference to `Test::text'
}
Run Code Online (Sandbox Code Playgroud)
错误消息是
/tmp/main-35f287.o: In function `main':
main.cpp:(.text+0x4): undefined reference to `Test::text'
main.cpp:(.text+0x13): undefined reference to `Test::text'
clang: error: linker command failed with exit code 1 (use -v to see invocation)
Run Code Online (Sandbox Code Playgroud)
好.让我们试着解决这个问题:我在struct体外添加一个定义:
#include <iostream>
struct Test { static constexpr char text[] = "Text"; };
constexpr char Test::text[] = "Text";
int main()
{ …Run Code Online (Sandbox Code Playgroud)