覆盖Base类无法正常工作

时间:2013-02-03 19:18:53

标签: c++ inheritance polymorphism

我正试图在C ++中覆盖这样的基类

class A:
    QWidget *getWidget();

class B: public A:
    using A::getWidget;
    QWidget *getWidget();

当我尝试使用它时:

A *test = new B();
test->getWidget();

这里返回A类的小部件。有没有办法获得小部件B?因为我不想从检查我的类开始并向下转到B来获取正确的小部件,所以我希望能够使用它类似于上面的代码片段。有什么建议吗?

2 个答案:

答案 0 :(得分:6)

首先,如果您想要对函数调用进行动态多态解析,则应将getWidget()声明为virtual。这应该可以解决您正在解决的特定问题。

其次,using A::getWidget没用,因为您要将A的函数getWidget()导入B的范围,{{1}}已经定义了一个具有相同名称的函数和签名。

答案 1 :(得分:1)

那是C ++代码吗?

class A
{
public:
    //you need the virtual keyword here
    virtual QWidget *getWidget();
    virtual ~A();
};

class B : public A
{
public:
    //you need using to overload a method from the base class, it's not needed for override
    QWidget *getWidget();
};

A *test = new B();
test->getWidget();
delete test;

LE:也不要忘记基类中的虚拟析构函数。

相关问题