C++构造函数:数字常量之前的预期标识符

C++ constructor: expected identifier before numeric constant

本文关键字:标识符 构造函数 数字 常量 C++      更新时间:2023-10-16

我正在尝试使用 SDL 用 c++ 编写游戏,但遇到了一个问题。我有一个蝙蝠课和一个游戏课。当我尝试创建一个 bat 对象并调用构造函数时,出现以下错误:

"错误:数字常量之前的预期标识符"

以下是源文件:

游戏.h

#ifndef GAME_H
#define GAME_H
#include "SDL.h"
#include "Bat.h"
class Game
{
    public:
        Game();
        Bat bat(0, 0);
    private:
};
#endif // GAME_H

蝙蝠

#ifndef BAT_H
#define BAT_H
class Bat
{
    public:
        Bat(int x, int y);
        int getX() {return x;}
        int getY() {return y;}
    private:
        int x, y;
};
#endif // BAT_H

蝙蝠.cpp

#include "Bat.h"
Bat::Bat(int x, int y)
{
}

你的意思是写吗

class Game
{
    public:
        Game() : bat(0, 0) {} // <<< or move that definition to your .cpp file
    private:
        Bat bat; // << you can't initialize the member here.
};

??

如果您尝试创建bat初始化的成员变量0,0请尝试以下操作:

class Game
{
    public:
        Game();
    private:
        Bat bat;
};
Game::Game() : bat(0, 0){
}