如何使用基类对象调用派生类方法?

问题描述

我明白这是如何朝着相反的方向发展的。但是出于各种原因我想使用基类对象来调用派生类方法

假设我们有 2 个类,共同代表一个人的数据(姓名和年龄):

class Person 
{
protected: 
    char* name;   /// may be more than just one. also,heared that std::string is more efficient
public: 
    /// constructors,operator=,destructors,methods and stuff...   
}

class Info: public Person
{
protected: 
    int age;  /// may be more than one parameter.
public:
    /// constructors,methods and stuff... 

   int get_age() const;   /// method i want to call with a class Person object
    {
        return y;
    }
}

由于这两个类是关于一个人的数据,而且我有一个 Person 对象,我也想使用这个对象来找出他的年龄(可能从它的派生类 Info 调用 get_age() 方法)>

看到一些带有纯虚方法的东西,但我不知道如何在 main 中正确调用该虚函数

我该怎么做? (如果您也能向我展示程序的主要内容,我将不胜感激)

解决方法

您可以通过在基类中将其声明为虚拟函数来确保派生类具有您想要调用的函数。通常使用“纯虚函数”(一个没有实现的函数)。

像这样:

class Person
{
protected:
    char* name;   /// may be more than just one. also,heared that std::string is more efficient
public:
    /// constructors,operator=,destructors,methods and stuff...

    // Pure Virtual Function
    virtual int get_age() const = 0;   /// force derived classes to implement

};

class Info: public Person
{
protected:
    int age;  /// may be more than one parameter.
public:
    /// constructors,methods and stuff...

   int get_age() const override   /// override here
    {
        return age;
    }
};