2015-08-08 39 views
0

我有以下:C++复杂类联静态constexpr类成员发出

头文件:

class CU 
{ 
    const char *u; 
public: 
    constexpr CU (const char *u) :u(u) {} 
    constexpr const char *c_str() const { return u; } ; 
    constexpr operator const char * () const { return u; } ; 
}; 

void test2 (const CU & r) ; 

class S 
{ 
public: 
    static constexpr CU u = CU("foo"); // linker error 
    /* 
    when I use the u in the normal constructor in a separate file I get a linker error 
    */ 
    S();  
}; 

源文件:

#include "test.hpp" 
#include <iostream> 

void test2 (const CU & r) 
{ 
    std::cerr << r; 
} 

S::S() 
{ 
    test2(S::u); 
} 

int main() { 
    S a; 
} 

从编译器输出

g++ -std=gnu++11 test.cpp test.hpp 
/tmp/cceBFmJM.o: In function S::S(): 
test.cpp:(.text+0x35): undefined reference to S::u 
collect2: error: ld returned 1 exit status 
Makefile:2: recipe for target 'test' failed 
make: *** [test] Error 1 

见Bugzilla的报告在这里: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=67155

+2

我没有看到'S :: u'的定义。使它成为'constexpr'并不意味着声明是一个定义。 – chris

+0

该对象在标题中内联定义。如果在头文件中使用它,如果它是交流字符串,它的工作原理,请参阅此处的代码https://github.com/h4ck3rm1k3/gcc-plugin-cpp-template/tree/constexpr/testcase – h4ck3rm1k3

+0

将此添加到c文件解决了这个问题。 constexpr CU S :: u; – h4ck3rm1k3

回答

1

答案是把它添加到源文件:

constexpr CU的s :: U;

谢谢@chris和@Drew Dormann。