错误:令牌之前的预期初始值设定项'.'

Error: expected initializer before '.' token

本文关键字:令牌 错误      更新时间:2023-10-16

我对使用类和C++的面向对象方面还很陌生,标题中出现了错误。

我正在用SDL写一个俄罗斯方块游戏。

我有一个形状的类定义。h

class shape
{
public:
    SDL_Surface *colour;
    int rotation1[4][4];
    int rotation2[4][4];
    int rotation3[4][4];
    int rotation4[4][4];
    bool load();
    void move();
    shape();
};

并且在主.h中,我已经包括了shapes.h和具有的类的定义实例

//Create shapes
shape O, T, S, L, R, Z, I;

我还为每个形状(如I.cpp(提供了单独的文件,因为每个形状都有不同的代码,用于将块颜色的图像加载到SDL_Surface颜色和块不同旋转的各种阵列上,所以我将其分离为每个块的一个文件。

在I.cpp中,我包含了main.h,并尝试为我设置如下加载函数:

bool I.load()
{
    //if loading the cyan square texture fails
    if ((I.colour = surface::onLoad("../Textures/cyanSquare.png")) == NULL)
    {
        //print error
        cout << "Unable to load cyanSquare.png";
        //return fail
        return false;
    }
    I.rotation1 = {{7,7,7,7},
                   {0,0,0,0},
                   {0,0,0,0},
                   {0,0,0,0}};
    I.rotation2 = {{0,0,7,0},
                   {0,0,7,0},
                   {0,0,7,0},
                   {0,0,7,0}};
    I.rotation3 = {{7,7,7,7},
                   {0,0,0,0},
                   {0,0,0,0},
                   {0,0,0,0}};
    I.rotation4 = {{0,0,7,0},
                   {0,0,7,0},
                   {0,0,7,0},
                   {0,0,7,0}};
    return true;
}

当我尝试编译这个(使用GCC(时,它在的I.cpp的第3行报告了一个错误

error: expected initializer before '.' token

我完全不知道这意味着什么,也找不到任何有用的搜索谷歌这个错误代码,所以任何帮助都将不胜感激。

这不是有效的C++。CCD_ 1是一个变量;不能为特定变量(bool I.load()(定义成员函数。也许你的意思是bool shape::load()

bool I.load()

不是吗bool shape::load()

我只是"形状"类型的一个实例。你怎么能在函数实现中使用"I",因为它对"I"实例一无所知!

你可能想这样做:1.添加一个带参数的构造来指定实例的图片:

class shape
{
public:
//....
    shape(const char* pImagePath);
private:
    const char* m_pImagePath;
};

并将构造函数实现为:

shape::shape(const char* image_path) : m_pImagePath(pImagePath) {}

然后您的load((可以实现为:

bool shape::load()
{
    //if loading the cyan square texture fails
    if ((colour = surface::onLoad(m_pImagePath)) == NULL)
    {
        cout << "Unable to load cyanSquare.png";
        return false;
    }
    rotation1 = {{7,7,7,7},
                 {0,0,0,0},
                 {0,0,0,0},
                 {0,0,0,0}};
    rotation2 = {{0,0,7,0},
                 {0,0,7,0},
                 {0,0,7,0},
                 {0,0,7,0}};
    rotation3 = {{7,7,7,7},
                 {0,0,0,0},
                 {0,0,0,0},
                 {0,0,0,0}};
    rotation4 = {{0,0,7,0},
                 {0,0,7,0},
                 {0,0,7,0},
                 {0,0,7,0}};
    return true;
}

创建实例"I"如下:

shape I("../Textures/cyanSquare.png");