下面的程序給我一個鏈接時錯誤:有一個constexpr靜態字符串給出一個鏈接錯誤
#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
體外的定義:
#include <iostream>
struct Test { static constexpr char text[] = "Text"; };
constexpr char Test::text[] = "Text";
int main()
{
std::cout << Test::text << std::endl;
}
鏘給我下面的錯誤消息。
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[]; };
還有狗咬自己尾巴。 :(
有沒有辦法使用在類中聲明的編譯時常量字符數組?原因是,我想要一個類內的數據,是我需要一個類型traits類,可以幫助我做模板的東西。
你是不是隻是簡單的'結構測試{靜態常量字符文本[] =「文本」; }; '? –
你已經嘗試了兩種選擇 - 課堂外的初始化器,無論是內部還是外部。現在,有第三個替代方案... –
這工作正常:'結構測試{靜態constexpr自動文本=「文本」; };' – vincentp