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