2016-01-14 19 views
5

下面的程序給我一個鏈接時錯誤:有一個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類,可以幫助我做模板的東西。

+0

你是不是隻是簡單的'結構測試{靜態常量字符文本[] =「文本」; }; '? –

+1

你已經嘗試了兩種選擇 - 課堂外的初始化器,無論是內部還是外部。現在,有第三個替代方案... –

+1

這工作正常:'結構測試{靜態constexpr自動文本=「文本」; };' – vincentp

回答

8

應該工作:

#include <iostream> 

struct Test { static constexpr char text[] = "Text"; }; 
constexpr char Test::text[]; 

int main() 
{ 
    std::cout << Test::text << std::endl; 
} 

在標準(n4140§9.4.2/ 3),你可以找到:

A static data member of literal type can be declared in the class definition with the constexpr specifier; if so, its declaration shall specify a brace-or-equal-initializer in which every initializer-clause that is an assignment-expression is a constant expression. [ Note: In both these cases, the member may appear in constant expressions. —end note ] The member shall still be defined in a namespace scope if it is odr-used (3.2) in the program and the namespace scope definition shall not contain an initializer.

+0

只有一個初始化初始化分配。 –

+0

適合我!謝謝! –

2

正如評論所說,這個版本工作正常:

struct Test { static constexpr auto text = "Text"; }; 

text將是一個const char*,而不是char[]

+0

爲什麼不能在其中創建一個'const char [5]'?我的意思是爲什麼有這麼多的差異?這很煩人。這使得它對我的目的無法使用。 –

相關問題