对对象指针调用成员函数
Call member function on object pointer
我正在尝试用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]);
?
相关文章:
- 对RValue对象调用的LValue ref限定成员函数
- 为什么使用 "this" 指针调用派生成员函数?
- 将公共但非静态的成员函数与ALGLIB集成
- 使用指向成员的指针将成员函数作为参数传递
- 将重载的成员函数传递给函数模板
- 我不小心调用了一个没有自己类对象的成员函数.但这是怎么回事呢
- 如何在C++中使用非静态成员函数作为回调函数
- C++错误C2600:无法定义编译器生成的特殊成员函数(必须首先在类中声明)
- 关联容器的下界复杂性:成员函数与非成员函数
- 在 C++ 中用派生类型重写成员函数
- 链表的泛型函数remove()与成员函数remove)
- 如何将lambda作为模板类的成员函数参数
- constexpr构造函数需要常量成员函数时出现问题
- 将自由函数绑定为类成员函数
- 区分非成员函数和头文件中的成员函数
- 如何从子成员函数修改父公共成员变量
- 保留对其他类的成员函数的引用
- 在运算符重载定义中使用成员函数(const错误)
- 内联如何影响模块接口中的成员函数
- 将成员函数指针作为参数传递给模板方法