c++ - cpp从需要父类(super class)对象的函数访问子类对象方法

标签 c++ inheritance subclass superclass

我写了下面的代码:

// constructors and derived classes
#include <iostream>
using namespace std;

class Mother
{
  public:
    int age;
    Mother()
    {
        cout << "Mother: no parameters: \n"
             << this->age << endl;
    }
    Mother(int a)
    {
        this->age = a;
    }
    void sayhello()
    {
        cout << "hello my name is clair";
    }
};

class Daughter : public Mother
{
  public:
    int age;
    Daughter(int a)
    {
        this->age = a * 2;
    };
    void sayhello()
    {
        cout << "hello my name is terry";
    }
};

int greet(Mother m)
{
    m.sayhello();
}

int main()
{
    Daughter kelly(1);
    Son bud(2);
    greet(kelly);
}

我的问题是: 由于 kelly 是从 Mother 派生的类的实例,因此我可以将它传递给需要 mother 类型对象的函数,即。迎接。我的问题是,是否可以从 greet 中调用 sayhello 函数,这样它会说 它会说“你好我的名字是特里”而不是“你好我的名字是克莱尔”。

最佳答案

您所要求的称为“多态行为”(或“动态调度”),它是 C++ 的基本功能。要启用它,您需要做几件事:

  1. 使用 virtual 关键字标记您的 sayhello() 方法(即 virtual void sayhello() 而不仅仅是 void sayhello())

  2. greet() 方法的参数更改为按引用传递或按指针传递,以避免对象切片问题(即 int greet(const Mother & m) 而不是 int greet(Mother m))

完成后,编译器将根据 m 参数的实际对象类型,智能地选择在运行时调用哪个 sayhello() 方法,而不是根据 greet 函数的参数列表中明确列出的类型在编译时对选择进行硬编码。

关于c++ - cpp从需要父类(super class)对象的函数访问子类对象方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54209079/

相关文章:

c++ - 取实时网络摄像头帧的平均值

java - 无法调用初始化为父类(super class)的 ArrayList 中派生类的方法

python - 从不同目录实例化Python子类

c++ - 是否需要注册一个 dll 才能使用它

c++ - 如何为模板类的 const ref 成员定义 move 赋值运算符

java - 扩展类和静态变量

c# - 从在其构造函数中接受参数的基类继承的单例类?

swift - 有没有办法将快速方法注释为需要调用其父类(super class)的实现

javascript - Fabric.js 从现有形状创建新类 fromObject 错误

c++ - 如何删除文本文件中的最后一个字符 C++