【问题标题】:Call member function on object pointer在对象指针上调用成员函数
【发布时间】:2016-04-09 08:05:25
【问题描述】:

我正在尝试用 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 类中,我想定义一个函数,对游戏窗口“objects”数组中保存的所有对象调用“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()”函数,所以我知道这不是问题所在。任何帮助将不胜感激。

【问题讨论】:

  • 你有一个 char* 指针数组,而不是游戏对象或你想要的任何东西。

标签: c++ arrays oop polymorphism member-functions


【解决方案1】:

我想我明白了。我创建了一个名为 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();
    }
}

我运行了它,它没有任何错误。

【讨论】:

    【解决方案2】:

    Game_Window::objects 的类型是char**(指向char 的指针)。因此objects[i]ith 指针,而指针没有print() 方法,这就是(objects[i])-&gt;print(); 失败并出现上述错误的原因。

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

    【讨论】:

      猜你喜欢
      • 2018-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-05
      • 1970-01-01
      • 1970-01-01
      • 2015-01-07
      • 2021-06-06
      相关资源
      最近更新 更多