2014-09-25 59 views
0

我無法編譯它。我不知道發生了什麼,這對我來說似乎很好。該錯誤,我得到:錯誤C2143和錯誤C2059缺少「;」之前「{」

error C2059: syntax error "{" 
error C2143: syntax error: missing ";" before "}" 
error C2143: syntax error: missing ";" before "}" 

X.h

class X 
    { 
     friend symbol; 
    public: 
     X(); 
    private: 
     int tab[4][3]; 
    }; 

X.cpp

X::X() 
{ 
    tab[4][3]={{0,1,0},{1,0,1},{2,-1,0},{3,0,-1}}; 
} 

哪裏出了問題?

+0

你使用的是什麼版本的VC++? VC++ 6,VS2005 C++,VS2010 C++ ..等? – 2014-09-25 19:16:37

回答

0

什麼你正在嘗試做的基本上可以用C++ 11標準的C++編譯器完成。不幸的是,你正在使用Visual C++(不知道哪個版本),但這種事情將無法正常發佈的VC + +。曾VC++一直充分 C++ 11兼容這會工作:

private: 
    int tab[4][3] {{0,1,0},{1,0,1},{2,-1,0},{3,0,-1}}; 
}; 

正巧下面的代碼,並使用C++ 11兼容的編譯器的工作,但它也適用於VC++從VS2013開始。可能適合你更好的東西用std::array

#include <array> 

class X { 
    friend symbol; 
    public: 
    X(); 
    private: 
    // Create int array with 4 columns and 3 rows. 
    std::array<std::array<int, 3>, 4> tab; 
}; 


X::X() 
{ 
    // Now initialize each row 
    tab[0] = { {0, 1, 0} }; // These assignments will not work on Visual studio C++ 
    tab[1] = { {1, 0, 1} }; //  earlier than VS2013 
    tab[2] = { {2, -1, 0} }; // Note the outter { } is used to denote 
    tab[3] = { {3, 0, -1} }; //  class initialization (std::arrays is a class) 

    /* This should also work with VS2013 C++ */ 
    tab = { { { 0, 1, 0 }, 
       { 1, 0, 1 }, 
       { 2, -1, 0 }, 
       { 3, 0, -1 } } }; 
} 

我一般用vector到位像int tab[4][3];該陣列可以被視爲向量的向量。

#include <vector> 

class X { 
    friend symbol; 
    public: 
    X(); 
    private: 
    std::vector < std::vector <int>>tab; 
}; 


X::X() 
{ 
    // Resize the vectors so it is fixed at 4x3. Vectors by default can 
    // have varying lengths. 
    tab.resize(4); 
    for (int i = 0; i < 4; ++i) 
     tab[i].resize(3); 

    // Now initialize each row (vector) 
    tab[0] = { {0, 1, 0} }; 
    tab[1] = { {1, 0, 1} }; 
    tab[2] = { {2, -1, 0} }; 
    tab[3] = { {3, 0, -1} }; 
} 
4

您的tab[4][3]={{0,1,0},{1,0,1},{2,-1,0},{3,0,-1}};有幾個問題。

  1. tab[4][3]嘗試來指tab一個元件,而不是整個陣列。
  2. 它索引超出範圍 - tab定義爲tab[4][3],合法指數從tab[0][0]tab[3][2]
  3. 你試圖分配一個數組,即使你修復前面的數組也是不可能的。
1

你可以使用這個語法,如果C++ 11可供您

X() : tab {{0,1,0},{1,0,1},{2,-1,0},{3,0,-1}} {} 
+0

Visual C++ 2013(官方發佈)尚未完全符合C++ 11標準,因此失敗。先前版本的VS C++不太合規 – 2014-09-25 18:53:05

相關問題