类继承和使用指针

Class inheritance and working with pointers

本文关键字:指针 继承      更新时间:2023-10-16

当发现我可以使用基类指针来使用派生类时,我并不感到惊讶,如下所示(非常简单(:

class Base
{
    protected:
    int m_value;
    public:
    Base(int value)
        : m_value(value)
    {
    }
    const char* getName() { return "Base"; }
    int getValue() { return m_value; }
};
class Derived: public Base
{
    public:
    Derived(int value)
        : Base(value)
    {
    }
    const char* getName() { return "Derived"; }
    int getValueDoubled() { return m_value * 2; }
};

创建对象派生类后会发生什么情况?如果我使用

Base &rBase = derived;

我将使用在基类中确定的此类方法。为什么?这是否意味着派生类实际上由基类的第一个确定的 getName(( 组成,但现在只使用重载方法,如果我们愿意,那么我们可以通过基类上的指针调用 origin 方法?请用指针和地址来解释我。

在C++中,成员函数不是虚拟的,除非声明如此。

这意味着,在您的情况下,如果您调用 rBase.getName() ,因为rBase的类型是Base&,则无论rBase引用的对象具有什么派生类型,都将调用Base::getName()函数。

如果要动态调度,则必须声明函数 virtual

virtual const char* getName() { return "Base"; }

有了这个,调用rBase.getName() ,将查看实际类型rBase引用的对象,并且 - 如果这是Derived - 调用Derived::getName()

顺便说一句,当您要覆盖虚拟函数时,请使用 override 关键字。然后编译器可以帮助您查找错误。在您的情况下,您是否在 Derived 中使用它,例如:

const char* getName() override { return "Derived"; }

你会得到一个错误,比如

 error: only virtual member functions can be marked 'override'

并且,请注意 @scohe001 给出的建议并使用 std::string 而不是 char*,除非您有充分的理由需要 C 样式字符串。