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

C++ cpp从需要超类对象的函数访问子类对象方法,c++,inheritance,subclass,superclass,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;

我编写了以下代码:

// 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);
}
//构造函数和派生类
#包括
使用名称空间std;
班主任
{
公众:
智力年龄;
母亲()
{

CUT

你所要的是“多态行为”(或“动态调度”),它是C++的基本特征。要启用它,你需要做两件事:

  • virtual
    关键字标记
    sayhello()
    方法(即
    virtual void sayhello()
    而不仅仅是
    void sayhello()

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


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

    您要求的是所谓的“多态行为”(或“动态分派”)它是C++的一个基本特性,为了实现它,您需要做两件事:

  • virtual
    关键字标记
    sayhello()
    方法(即
    virtual void sayhello()
    而不仅仅是
    void sayhello()

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


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

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