对对象指针调用成员函数

Call member function on object pointer

本文关键字:成员 函数 调用 指针 对象      更新时间:2023-10-16

我正在尝试用C++编写一个简单的游戏,目前我的game_Window类包含一组指向游戏对象的指针,如下所示:

class Game_Window {
private:
    int width;
    int height;
    int num_objects;
public: 
    char** objects;
/* The rest of the class goes here */
}

在我的Game_Window类中,我想定义一个函数,对游戏窗口"对象"数组中的所有对象调用"print()"函数,如下所示。

void Game_Window::print_objects() {
    for (int i = 0; i < num_objects; i++) {
        (objects[i])->print();        /* THE PROBLEM IS HERE */
    }
}

当我编译时,我得到以下错误:

game_window.cpp:29:15: error: member reference base type 'char' is not a structure or union
                (objects[i])->print();
                ~~~~~~~~~~~~^ ~~~~~
1 error generated.

我的游戏中的所有对象都有一个"print()"函数,所以我知道这不是问题所在。任何帮助都将不胜感激。

我想我想通了。我创建了一个名为Game_Object的类,我的所有游戏对象都将继承该类,并给它一个print()方法。

class Game_Object {
private:
    Location location;
public: 
    Game_Object();
    Location *get_location() { return &location; }
    void print();
};
class Diver : public Game_Object {
public:
    explicit Diver(int x, int y);
};

class Game_Window {
private:
    int width;
    int height;
    int num_objects;
public: 
    Game_Object** objects;

    explicit Game_Window(int width, int height);
    ~Game_Window();
    int get_width() { return width; }
    int get_height() { return height; }
    int get_object_count() { return num_objects; }
    bool add_object(Game_Object object);    
    void print_objects();
};

print()的调用现在是:

void Game_Window::print_objects() {
    for (int i = 0; i < num_objects; i++) {
        objects[i]->print();
    }
}

我跑了它,它没有失误。

Game_Window::objects的类型为char**(指向指向char的指针的指针)。因此,objects[i]i个指针,并且指针没有print()方法,这就是为什么(objects[i])->print();以所描述的错误失败的原因。

也许您打算使用print(objects[i]);