2016-08-11 11 views
2

私はこのコードに何かがひどく間違っていると思います。それはコンパイルされますが、リンクされません。C++タプルリンクの問題:未定義の参照

#include <iostream> 
#include <tuple> 

class Table_class 
{ 
    public: 
    constexpr static std::tuple<int, unsigned int, unsigned short> table[3] 
    = {std::make_tuple(1, 2, 3), 
     std::make_tuple(4, 5, 6), 
     std::make_tuple(7, 8, 9)}; 
}; 

int main() 
{ 
    std::cout << std::get<0>(Table_class::table[0]); 
    return 0; 
} 

現れるエラーがこれです:

[31m/tmp/ccDiIuPv.o: In function `main': 
file.cpp:(.text+0x5): undefined reference to `Table_class::table' 
collect2: error: ld returned 1 exit status 

Compilation Failed 

どのようにこれを修正することができますか?

+2

の可能な重複(http://stackoverflow.com/questions/5019856/c-initialize-static-variables-in-class) – Ari0nhh

答えて

4

大したことはありません。あなたのコードはC++で完全に正当なものになります17。しかし、C++ 17の前に、静的constexprのデータメンバは、クラスの外で定義されたので、どこかで見つけて、次の定義を追加する必要があります

constexpr std::tuple<int, unsigned int, unsigned short> Table_class::table[3]; 

demo

いつものように、変数定義はヘッダーファイル内にあってはなりません。

+0

解決策は問題を解決しますが、.hまたは.cppファイルの一部として使用すると、それを呼び出すルーチンでその行を定義する必要があるという欠点があります。 C++のために指が交差17! – bowzee

1

リンクエラーの一般的な原因です。 リンカーが見つけさせるために、クラス定義の外でテーブルを定義する必要があります。 簡略化した例:[?C++クラスの静的変数を初期化]

#include <iostream> 
#include <tuple> 

class Table_class 
{ 
    public: 
    constexpr static std::tuple<int, unsigned int, unsigned short> table = std::make_tuple(1, 2, 3); 

}; 

constexpr std::tuple<int, unsigned int, unsigned short> Table_class::table; 
int main() 
{ 
    std::cout << std::get<0>(Table_class::table); 
    return 0; 
}