【问题标题】:error C2143 and error C2059 missing ";" before "{"错误 C2143 和错误 C2059 缺少“;”前 ”{”
【发布时间】:2014-09-25 18:02:09
【问题描述】:

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

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

哪里出了问题?

【问题讨论】:

  • 您使用的是哪个版本的 VC++? VC++6、VS2005 C++、VS2010 C++ ..等?

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


【解决方案1】:

您的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. 您正在尝试分配一个数组,这(即使您修复了前面的问题)是不可能的。

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • Visual C++ 2013(正式版)尚未完全兼容 C++11,因此失败了。以前版本的 VS C++ 不太兼容
    【解决方案3】:

    您尝试做的事情基本上可以使用符合 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} };
    }
    

    【讨论】:

      猜你喜欢
      • 2011-10-03
      • 2011-05-17
      • 1970-01-01
      • 2012-02-22
      • 2013-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多