visual-studio - 在C++ 类中初始化vector失败的问题?
PHP中文网
PHP中文网 2017-04-17 14:35:53
0
2
625

初学C++,我试着写一个贪吃蛇游戏,代码如下:

#include #include  #include  #include  #include #include using namespace std; class Snake { friend void displaySnake(Snake &s); public: using ssbody = pair, string>; Snake() = default; vector body() const { return snakebody; } private: int lengh=1; //蛇的长度 vector snakebody{make_pair(make_pair(10, 10), "●")}; //蛇的位置和符号 };
void gotoxy(int x, int y) { HANDLE h;//句柄,对象的索引 COORD c;//结构体,坐标值 c.X = x; c.Y = y; h = GetStdHandle(STD_OUTPUT_HANDLE); SetConsoleCursorPosition(h, c); } void displaySnake(Snake &s) //打印蛇 { for (auto &c : s.snakebody){ gotoxy(c.first.first, c.first.second); //设置光标到保存的坐标处 gotoxy我省略了 cout << c.second; } }

我想用vector snakebody来保存蛇的身体,包括蛇每个点的位置和符号(●代表蛇头,○代表蛇尾)。我希望snakebody开始时总是有一个蛇头(在坐标(10,10)处,符号是●),于是我用make_pair(make_pair(10, 10), "●")初始化snakebody。但是我在main函数中调用时总是失败,main函数代码:

int main() { Snake s; displaySnake(s); }

错误说明:

error C2664: “std::vector>::vector(std::initializer_list,std::string>>,const std::allocator<_Ty> &)”: 无法将参数 1 从“std::pair,const char *>”转换为“const std::allocator<_Ty> &”
PHP中文网
PHP中文网

认证0级讲师

reply all (2)
洪涛
void displaySnake(Snake &s) //打印蛇 { //重复使用了s for (auto &s : s.snakebody){ gotoxy(s.first.first, s.first.second); //设置光标到保存的坐标处 cout << s.second; } }

for (auto &s : s.snakebody)S is used repeatedly here. . . . . .

Run results

    Ty80

    Move the initialization into the constructor.

    Setting initial values for member variables is only applicable to literal types. initializer_list is too much thought.

      Latest Downloads
      More>
      Web Effects
      Website Source Code
      Website Materials
      Front End Template
      About us Disclaimer Sitemap
      php.cn:Public welfare online PHP training,Help PHP learners grow quickly!