类继承和使用指针
Class inheritance and working with pointers
当发现我可以使用基类指针来使用派生类时,我并不感到惊讶,如下所示(非常简单(:
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 样式字符串。
相关文章:
- 关于C++中具有多重继承"this"指针的说明
- 共享指针继承,而不先显式强制转换
- 派生类是从基类继承 v 指针并仅使用它,还是也有自己的 v 指针?
- 使用智能指针附加的继承对象的深层复制
- 嵌套类、继承和C++中的共享指针
- 删除C++中的继承类指针数组
- 具有虚拟指针和继承的 CPP 类大小
- 钻石继承虚拟成员铸造与指针
- 当键是虚拟继承中涉及的基类指针时,对 std::unordered_map 项的访问崩溃
- 当依赖关系和依赖关系都是多态时,在哪个继承级别存储依赖关系指针?
- cppyy 继承包含智能指针的类
- 作为模板参数的成员函数指针在继承的成员函数上失败,如何以及为什么?
- 是否可以将成员作为指针继承
- C++14 不能调用从唯一指针继承的类的复制构造函数或运算符 =
- 是无限的Typedef函数指针继承
- 是否可以从 C++11 智能指针继承并覆盖相关运算符?
- 继承:使用从父指针继承的方法
- 使用智能指针继承的皮条
- 是覆盖返回类型所需的指针-继承
- 调用未从BaseClass指针继承的DerivedClass函数