以下程序给我一个链接时错误:
#include <iostream>
struct Test { static constexpr char text[] = "Text"; };
int main()
{
std::cout << Test::text << std::endl; // error: undefined reference to `Test::text'
}
错误信息是
/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)
好的。让我们尝试解决这个问题:我在struct
body:
#include <iostream>
struct Test { static constexpr char text[] = "Text"; };
constexpr char Test::text[] = "Text";
int main()
{
std::cout << Test::text << std::endl;
}
Clang 给我以下错误消息。
main.cpp:4:35: error: static data member 'text' already has an initializer
constexpr char Test::text[] = "Text";
^
main.cpp:3:50: note: previous initialization is here
struct Test { static constexpr char text[] = "Text"; };
哦,好吧,我想,现在我知道你想要什么了:
#include <iostream>
struct Test { static constexpr char text[]; };
constexpr char Test::text[] = "Text";
int main()
{
std::cout << Test::text << std::endl;
}
又报错了:
main.cpp:3:41: error: declaration of constexpr static data member 'text' requires an initializer
struct Test { static constexpr char text[]; };
狗在那里咬了自己的尾巴。 :(
有没有办法使用在类内部声明的编译时常量字符数组?我想要类中的数据的原因是我需要一个类型特征类来帮助我做模板的事情。