小编Avl*_*ath的帖子

继承混乱

好吧所以我一直在研究游戏引擎,我遇到了一个问题...目前我有一个类的层次结构(图像 - >动画 - >对象)所有这些都有一个方法get_type(),我有这个问题:

如果我使用new关键字声明派生类,或静态地,我得到所需的结果:

object instance;
cout << instance.get_type(); //returns an int value  

object* pointer = new(object);
cout << pointer->get_type();
Run Code Online (Sandbox Code Playgroud)

从上面的代码中,控制台输出3.该方法在对象中声明为:

图像类:

class image{
public:
  virtual int get_type();
};

int object::get_type(){
  return 1;
}
Run Code Online (Sandbox Code Playgroud)

动画类:

class animation: public image{
public:
  virtual int get_type();
};

int animation::get_type(){
  return 2;
}
Run Code Online (Sandbox Code Playgroud)

对象类:

class object: public animation{
public:
  virtual int get_type();
};

int object::get_type(){
  return 3;
}
Run Code Online (Sandbox Code Playgroud)

现在当我做这样的事情时出现了问题:

object* t = &object();
cout << t->get_type();  
Run Code Online (Sandbox Code Playgroud)

结果现在是1.

如果我从对象类的类声明中删除virtual关键字,它可以正常工作(代码的最后一位返回3) …

c++ inheritance

9
推荐指数
1
解决办法
161
查看次数

标签 统计

c++ ×1

inheritance ×1