【问题标题】:How to call a derived class method using a base class object?如何使用基类对象调用派生类方法?
【发布时间】:2021-07-05 16:38:58
【问题描述】:

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

假设我们有 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, operator=, destructors, methods and stuff... 

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

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

看到了一些纯虚方法,但我不知道如何在 main 中正确调用该虚函数。

我该怎么做? (如果您也可以向我展示程序的主要内容,我会很感激)。

【问题讨论】:

  • 您的 main 有正确的想法,尽管它的示例太不完整,无法解释为什么会得到意外的输出。
  • 如果人没有get_age方法,你怎么能调用它?
  • 另外你没有正确分配myinfo,应该是Info* myinfo = new Info;
  • 我看到很多指针,但在您的代码中没有创建一个对象。你能edit 你的问题包括minimal, reproducible example 吗?
  • 继承关系不对。不能合理地说Info Person。搭配组合效果更好。

标签: c++ class inheritance downcast pure-virtual


【解决方案1】:

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

像这样:

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, operator=, destructors, methods and stuff...

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

【讨论】:

  • 回答不好,报错:“无法分配抽象类型Person的对象
  • @RedIcs 不幸的是,我无法在一个简单的答案中教你所有关于C++ 中继承的工作原理。我建议阅读该主题。尤其是关于虚函数多态性
  • @Redlcs 答案很好而且正确。但是,标准中明确规定了语言的规则。如果你在不了解某些主题的情况下尝试编写代码,那么你很自然会遇到这样的错误。试试这个现在可以解决你的问题。但它不会给你增加任何东西。你应该好好学习多态性和虚拟调度机制。人 *p = 新信息;
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-03-28
  • 2021-09-10
  • 1970-01-01
  • 2013-04-11
  • 1970-01-01
  • 2016-01-01
  • 2013-09-28
相关资源
最近更新 更多