ошибка компиляции c ++ (требуется подстановка), проблема с потоком? - PullRequest
0 голосов
/ 03 августа 2020

Когда я компилирую код, он дает мне несколько ошибок, которые, как мне кажется, связаны с потоком, который я использую (в Game :: StartGame) для игры l oop. Из-за ошибки я думаю, что у меня есть некоторые ошибки с методом Car :: myListener (это слушатель ввода с клавиатуры), как я могу это исправить ?. Мне нужно использовать класс, я публикую под заголовком и cpp файл класса Game и класса Car (в проекте есть другие классы).

Game.h

#ifndef GAME_H
#define GAME_H
#include "Car.h"

class Game
{
    public:
        bool running;
        int count;
        int matrix[15][20];
    public:
        Game();
        void gotoXY(int x, int y);
        void drawCar(int x, int y);
        void drawEnemies(int x, int y);
        void drawNails(int x, int y);
        void resetBoard();
        void creaTab();
        int punteggio();
        void startGame();
};

#endif // GAME_H

Игра. cpp

#include "Game.h"
#include "Nail.h"
#include "EnemiesCar.h"
#include "Car.h"
#include <windows.h>
#include <iostream>
#include <thread>
#include <stdlib.h>     /* srand, rand */
#include <ctime>
using namespace std;

Game::Game(){
    running = true;
    count = 0;
}

void Game::gotoXY(int x, int y)
{
    COORD coord;
    coord.X = x;
    coord.Y = y;
    SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}

void Game::drawCar(int x, int y)
{
    if(y<20 && y>=-0){
        matrix[x][y]=1;
    }
}

void Game::drawEnemies(int x, int y)
{
    if(y<20 && y>=-0){
        matrix[x][y]=2;
    }
}

void Game::drawNails(int x, int y)
{
    if(y<20 && y>=-0){
        matrix[x][y]=3;
    }
}

void Game::resetBoard()
{
    for(int j=0;j<20;j++){
        for(int i=1;i<14;i++){
            matrix[i][j]=0;
        }
    }
}

void Game::creaTab()
{
    for(int j=0;j<20;j++){
        for(int i=0;i<15;i++){
            if(i==0 || i==14){
                    gotoXY(i,j);
                    cout<<"b";
            }else if(matrix[i][j]==1){
                    gotoXY(i,j);
                    cout<<"m";
            }else if(matrix[i][j]==2){
                    gotoXY(i,j);
                    cout<<"e";
            }else if(matrix[i][j]==3){
                    gotoXY(i,j);
                    cout<<"c";
            }else {
                gotoXY(i,j);
                cout<<" ";
            }
        }
    }
}

int Game::punteggio()
{
    count ++;
    return count;
}

void Game::startGame()
{
    //Car *mycar = new Car();
    Car mycar = Car();
    EnemiesCar myEnmCar = EnemiesCar();
    Nail nails = Nail();
    // starts the second thread (The input listener )
    thread myThread(&mycar.myListener, &mycar);

    // This is the game engine/game loop
    while(running){
        resetBoard();
        myEnmCar.appear();
        myEnmCar.draw();
        myEnmCar.move();

        nails.appear();
        nails.draw();
        nails.move();
        mycar.draw();
        mycar.checkCollusion(&myEnmCar,&running);

        creaTab();


        punteggio();
        gotoXY(20, 0);
        cout<<"Point: " << count ;
        /*gotoXY(20, 1);
        cout<<"Livello: 1" ;*/


        Sleep(50);
    }
    //The game ended

    //Show the Game Over
    Sleep(1000);
    system("cls");
    gotoXY(5,4);
    cout<<"GAME OVER!!!";
    gotoXY(0,0);
    Sleep(5000);

    // Kills the second thread
    myThread.detach();
}

Car.h

#ifndef CAR_H
#define CAR_H
#include "Game.h"
#include "EnemiesCar.h"

class Game;
class EnemiesCar;

class Car
{
    public:
        int xPos;
        int yPos;
        Game *games;
    public:
        Car();
        void draw();
        void moveLeft();
        void moveRight();
        void myListener(Car *c);
        void checkCollusion(EnemiesCar *EC, bool *running);

};

#endif // CAR_H

Car. cpp

#include "Car.h"
#include "Game.h"
#include "EnemiesCar.h"
#include <windows.h>
#include <iostream>
#include <stdlib.h>     /* srand, rand */
#include <ctime>
#include <thread>
using namespace std;

Car::Car(){
    xPos=2;
    yPos=17;
}

void Car::draw(){
    this->games->drawCar(xPos,yPos);
    this->games->drawCar(xPos-1,yPos+1);
    this->games->drawCar(xPos+1,yPos+1);
    this->games->drawCar(xPos,yPos+1);
    this->games->drawCar(xPos,yPos+2);
}

void Car::moveLeft(){
    if(xPos-2 <= 0){
        xPos = 2;
    }else{
        xPos = xPos - 2;
    }
}

void Car::moveRight(){
    if(xPos+2 >= 14){
        xPos = 12;
    }else{
        xPos = xPos + 2;
    }
}

void Car::myListener(Car* c)
{
    while(true){
            if (GetAsyncKeyState(VK_LEFT) & (0x8000 != 0)){
                    c->moveLeft();
                }
            else if (GetAsyncKeyState(VK_RIGHT) & (0x8000 != 0)){
                    c->moveRight();
                }
    }
}

void Car::checkCollusion(EnemiesCar *EC, bool *running){
    if((EC->xPos == xPos && EC->yPos > 15) || (EC->xPos-1 == xPos+1 && EC->yPos > 17) || (EC->xPos+1 == xPos-1 && EC->yPos > 17)){
        *running=false;
    }
}

ОШИБКИ

||=== Build: Release in ProgettoProgrammazione (compiler: GNU GCC Compiler) ===|
MinGW\lib\gcc\mingw32\5.1.0\include\c++\functional||In instantiation of 'struct std::_Bind_check_arity<void (Car::*)(Car*), Car*>':|
MinGW\lib\gcc\mingw32\5.1.0\include\c++\functional|1538|required from 'struct std::_Bind_simple_helper<void (Car::*)(Car*), Car*>'|
MinGW\lib\gcc\mingw32\5.1.0\include\c++\functional|1552|  required by substitution of 'template<class _Callable, class ... _Args> typename std::_Bind_simple_helper<_Func, _BoundArgs>::__type std::__bind_simple(_Callable&&, _Args&& ...) [with _Callable = void (Car::*)(Car*); _Args = {Car*}]'|
MinGW\lib\gcc\mingw32\5.1.0\include\c++\thread|142|required from 'std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = void (Car::*)(Car*); _Args = {Car*}]'|
ProgettoProgrammazione\src\Game.cpp|92|required from here|
MinGW\lib\gcc\mingw32\5.1.0\include\c++\functional|1426|error: static assertion failed: Wrong number of arguments for pointer-to-member|
MinGW\lib\gcc\mingw32\5.1.0\include\c++\functional||In instantiation of 'struct std::_Bind_simple<std::_Mem_fn<void (Car::*)(Car*)>(Car*)>':|
MinGW\lib\gcc\mingw32\5.1.0\include\c++\thread|142|required from 'std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = void (Car::*)(Car*); _Args = {Car*}]'|
ProgettoProgrammazione\src\Game.cpp|92|required from here|
MinGW\lib\gcc\mingw32\5.1.0\include\c++\functional|1505|error: no type named 'type' in 'class std::result_of<std::_Mem_fn<void (Car::*)(Car*)>(Car*)>'|
MinGW\lib\gcc\mingw32\5.1.0\include\c++\functional|1526|error: no type named 'type' in 'class std::result_of<std::_Mem_fn<void (Car::*)(Car*)>(Car*)>'|
||=== Build failed: 4 error(s), 7 warning(s) (0 minute(s), 0 second(s)) ===|

1 Ответ

0 голосов
/ 04 августа 2020

Ошибки показывают несовместимость типов и неправильное количество аргументов при создании экземпляра класса thread: thread myThread(&mycar.myListener, &mycar);.

Измените эту строку на thread myThread(&Car::myListener, &mycar, &blah);. Замените blah любым экземпляром Car, который вы хотите передать в качестве аргумента своему методу mycar.myListener.

То есть, при создании потока с использованием метода объекта первым аргументом должна быть подпись метода, второй аргумент объект, затем аргументы этого метода.

См .: https://en.cppreference.com/w/cpp/thread/thread/thread

...