繁体   English   中英

cpp从需要超类对象的函数访问子类对象方法

[英]cpp access subclass object methods from function that requires superclass object

我写了以下代码:

// 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类型的对象的函数,例如。 迎接。 我的问题是,是否可以从打招呼中调用sayhello函数,使其说“你好,我叫特里”而不是“你好,我叫克莱尔”。

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM