【问题标题】:cpp access subclass object methods from function that requires superclass objectcpp 从需要超类对象的函数访问子类对象方法
【发布时间】:2019-06-10 01:38:31
【问题描述】:

我写了以下代码:

// 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 函数,这样它会说 它会说“你好我的名字是特里”而不是“你好我的名字是克莱尔”。

【问题讨论】:

  • 顺便说一句,在Daughter 类中声明int age; 可能没有意义,因为该变量已经存在于Mother 类中。如果你也在Daughter 类中声明它,那么每个Daughter 都会有两个年龄,这可能不是你想要的。更好的方法是像这样编写Daughter 构造函数,以便将a 参数传递给Mother 的构造函数:Daughter(int a) : Mother(a*2) {}
  • 这种继承设置意味着每个Daughter也是一个Mother。这没有意义,但大概是因为这只是一个例子。

标签: c++ inheritance subclass superclass


【解决方案1】:

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

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

  2. greet() 方法的参数更改为 pass-by-reference 或 pass-by-pointer,以避免对象切片问题(即 int greet(const Mother &amp; m) 而不是 int greet(Mother m)

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

【讨论】:

    猜你喜欢
    • 2017-09-13
    • 1970-01-01
    • 2016-01-16
    • 1970-01-01
    • 2016-01-22
    • 1970-01-01
    • 2018-06-03
    • 2011-04-05
    • 2013-12-03
    相关资源
    最近更新 更多