【问题标题】:Calling a method of a subclass instance in an array调用数组中子类实例的方法
【发布时间】:2014-10-14 02:47:16
【问题描述】:

我开始使用 C++ 中的继承,但如果子类位于其超类的元素数组中,我不知道如何从子类调用方法。当我尝试调用子类方法时,它只是调用了超类方法。

这是我在 main.cpp 中的代码:

#include "SDL.h"
#include <iostream>
#include "shape.h"
#include "rectangle.h"

SDL_Surface * screen;
bool running = true;

rectangle Rectangle;
shape * Shapes[] = { &Rectangle };    // The array Shapes is initialized containing Rectangle

int main(int argc, char** argv) {
    screen = SDL_SetVideoMode(640, 480, 32, SDL_HWSURFACE);
    while (running) {
        // Rectangle.draw(screen);    This calls the rectangle draw method fine
        Shapes[0]->draw(screen);   // This calls the shape draw method instead
    }

    return 0;
}

shape 和 rectangle 是我正在使用的两个类;矩形是形状的子类。 shape 和 rectangle 都有draw() 函数。 shape 中的 draw 方法是空的,所以调用时什么也没有发生。 rectangle 中的 draw 方法只包含SDL_Quit(),所以如果调用它,SDL_Surface 屏幕将关闭。但是当我调用Shapes[0]-&gt;draw(screen) 时,它会调用shapes 类而不是矩形类中的draw 方法,即使Shapes[0] 是矩形的一个实例。当我在 Rectangle 对象上调用 draw() 时,它会从矩形调用 draw() 方法。这是为什么呢?

【问题讨论】:

  • 请告诉我们这两个类的定义。我猜要么这两种方法都不是虚拟的,要么它们的签名不同。

标签: c++ arrays inheritance subclass


【解决方案1】:

您必须将任何可以被子类覆盖的函数声明为virtual

class Shapes {
  // Some implementation information...
  virtual void draw(SDL_Surface *screen);
};

class Rectangle : public Shapes {
  // This method will override the Shapes version.
  // You do not have to declare it virtual, IIRC, but it's advisable.
  virtual void draw(SDL_Surface *screen);
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-18
    • 2021-08-28
    • 2015-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多