C++ 使用constexpr静态字符串会导致链接器错误
以下程序给了我一个链接时间错误:C++ 使用constexpr静态字符串会导致链接器错误,c++,string,c++11,constexpr,typetraits,C++,String,C++11,Constexpr,Typetraits,以下程序给了我一个链接时间错误: #include <iostream> struct Test { static constexpr char text[] = "Text"; }; int main() { std::cout << Test::text << std::endl; // error: undefined reference to `Test::text' } 嗯。让我们尝试解决这个问题:我在struct主体之外添加了一个定义
#include <iostream>
struct Test { static constexpr char text[] = "Text"; };
int main()
{
std::cout << Test::text << std::endl; // error: undefined reference to `Test::text'
}
嗯。让我们尝试解决这个问题:我在struct
主体之外添加了一个定义:
#include <iostream>
struct Test { static constexpr char text[] = "Text"; };
constexpr char Test::text[] = "Text";
int main()
{
std::cout << Test::text << std::endl;
}
哦,好吧,我想,现在我知道你想要什么了:
#include <iostream>
struct Test { static constexpr char text[]; };
constexpr char Test::text[] = "Text";
int main()
{
std::cout << Test::text << std::endl;
}
在那里,狗咬自己的尾巴(
有没有一种方法可以使用类内声明的编译时常量字符数组?原因是,我需要类内的数据,因为我需要一个类型特征类来帮助我完成模板工作。应该可以:
#include <iostream>
struct Test { static constexpr char text[] = "Text"; };
constexpr char Test::text[];
int main()
{
std::cout << Test::text << std::endl;
}
#包括
结构测试{static constexpr char text[]=“text”;};
constexpr char Test::text[];
int main()
{
std::cout如评论中所述,此版本运行良好:
struct Test { static constexpr auto text = "Text"; };
但是text
将是const char*
而不是char[]
你的意思是简单的struct Test{static const char text[]=“text”;
?你已经尝试了两个选项-类外的初始值设定项,包括内部和外部。现在,有第三个选择……这很好:struct Test{static constexpr auto text=“text”;};
@vincentp Nice。这是最简洁的书写方式。避免重复。值得接受。@vincentp是一个公认的答案。@vincentp跟进您的评论,我只问了这个问题一个初始化赋值。对我有效!谢谢!为什么制作const char[5]不起作用
退出?我的意思是为什么会有这么大的不同?这很烦人。这使它无法用于我的目的。
main.cpp:3:41: error: declaration of constexpr static data member 'text' requires an initializer
struct Test { static constexpr char text[]; };
#include <iostream>
struct Test { static constexpr char text[] = "Text"; };
constexpr char Test::text[];
int main()
{
std::cout << Test::text << std::endl;
}
struct Test { static constexpr auto text = "Text"; };