2014-09-25 191 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