错误C2143和错误C2059缺少“;”在“{”之前

时间:2014-09-25 18:02:09

标签: c++ arrays visual-c++ multidimensional-array

我无法编译它。我不知道发生了什么事,对我来说似乎不错。我得到的错误:

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}};
}

哪里出了问题?

3 个答案:

答案 0 :(得分: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 :(得分:1)

如果您可以使用C ++ 11,则可以使用此语法

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

答案 2 :(得分: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标准的编译器,但它也适用于从VS2013开始的VC ++。可能更适合您的方法是使用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} };
}
相关问题