C++ 编译vector-C+类型的类的私有成员时出错+;
我正在为扫雷游戏创建一个类。该类不接受任何参数。私有成员在类内初始化。我的目标是初始化整数的二维向量C++ 编译vector-C+类型的类的私有成员时出错+;,c++,class,vector,C++,Class,Vector,我正在为扫雷游戏创建一个类。该类不接受任何参数。私有成员在类内初始化。我的目标是初始化整数的二维向量 using namespace std; class Minesweeper { public: //This class takes no parameters //Other methods will be here private: int rows = 20; int cols = 20; vector < vector <int&
using namespace std;
class Minesweeper {
public:
//This class takes no parameters
//Other methods will be here
private:
int rows = 20;
int cols = 20;
vector < vector <int>> theBoard(rows, vector<int>(cols));
};
使用名称空间std;
级扫雷艇{
公众:
//这个类不接受任何参数
//其他方法也会在这里
私人:
int行=20;
int cols=20;
向量theBoard(行,向量(cols));
};
我收到的编译错误如下:(都与向量初始化一致)
我不理解上述错误。我相信我在创建二维向量时使用了正确的语法。谢谢你的帮助 向类中添加构造函数。比如说,
class Minesweeper
{
public:
Minesweeper()
: rows(20),
cols(20),
theBoard(rows, vector<int>(cols))
{
}
private:
int rows, cols;
vector<vector<int>> theBoard;
};
级扫雷舰
{
公众:
扫雷艇()
:第(20)行,
科尔斯(20),
电路板(行、向量(列))
{
}
私人:
int行,cols;
矢量电路板;
};
这是一个“MVP”(最烦人的解析)示例。有关此问题的更多信息,请参阅此问题的副本
然而,我仍然在这里给出一个关于如何正确初始化主板的答案,因为通常情况下,您会这样写:
vector<vector<int>> theBoard{rows, vector<int>{cols}};
您可以将
rows
和cols
从int
更改为size\u t
,但不建议对数量使用size\u t
(或通常使用无符号整数)。(<代码> vector < /COD>使用一个无符号整数,它的大小几乎是C++中的语言缺陷,现在它不能被修复,因为它会破坏太多代码。)/P>这里不需要构造函数。所有成员都已正确初始化。@Nikos,theBoard
是一个成员变量,而不是一个方法。这也会起作用:vector theBoard{static_cast(rows),vector{cols}代码>这避免了编写ctor的需要。
vector<vector<int>> theBoard{static_cast<size_t>(rows), vector<int>{cols}};