search

Home  >  Q&A  >  body text

visual-studio - 在C++ 类中初始化vector失败的问题?

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

#include<iostream>
#include <conio.h>
#include <windows.h>
#include <string>
#include<vector>
#include<utility>
using namespace std;


class Snake
{
    friend void displaySnake(Snake &s);

public:
    using ssbody = pair<pair<int, int>, string>;     
    Snake() = default;

    vector<ssbody> body() const { return snakebody; }

private:
    int lengh=1;   //蛇的长度
    vector<ssbody> 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<ssbody> snakebody 来保存蛇的身体,包括蛇每个点的位置和符号(●代表蛇头,○代表蛇尾)。我希望snakebody开始时总是有一个蛇头(在坐标(10,10)处,符号是●),于是我用make_pair(make_pair(10, 10), "●") 初始化snakebody。但是我在main函数中调用时总是失败,main函数代码:

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

错误说明:

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

reply all(2)I'll reply

  • PHP中文网

    PHP中文网2017-04-17 14:37:53

    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

    reply
    0
  • PHP中文网

    PHP中文网2017-04-17 14:37:53

    Move the initialization into the constructor.

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

    reply
    0
  • Cancelreply