指向子类对象的父类的继承和指针

时间:2019-09-04 06:14:30

标签: c++ inheritance

所以我有以下代码:

#include <iostream>

using namespace std;

class Parent
{
    int x;
    public:
    Parent(){x=10;}
    void f(){cout<<x;}
};

class Child: public Parent
{
  int x;
  public:
  Child(){x=20;}
  void f(){cout<<x;}
};

int main()
{
    Parent *pp;
    Child c;

    pp=&c;

    pp->f();

    return 0;
}

如您所见,我有两个类,从父类公开继承的父类和子类,所以我想看看如何使用指向父类的指针。

我认为可以像我在main中一样使用指向父类的指针并将其用于子对象上,但是,每当我运行此代码时,它都会打印出10,这是我拥有的值对于父类变量x,考虑到我使pp指向子对象,它不应该调用子类中定义的函数f(),因此应该打印20的值。任何帮助表示赞赏!

2 个答案:

答案 0 :(得分:1)

方法f必须是虚拟的。首先阅读this reference可能会有帮助。

#include <iostream>

using namespace std;

class Parent
{
    int x;
    public:
    Parent(){x=10;}
    virtual void f(){cout<<x;}
 // ^^^^^^^ see this 
};

class Child: public Parent
{
   int x;
   public:
   Child(){x=20;}
   virtual void f(){cout<<x;}
// ^^^^^^^ and this
// or since C++11 with override:
// void f() override {cout<<x;}

};

int main()
{
    Parent *pp;
    Child c;

    pp=&c;

    pp->f();

    return 0;
}

Demo

答案 1 :(得分:1)

代码中至少有两个问题。

首先,必须至少在f()类中将函数virtual声明为Parent(对于C ++ 11和更高版本,最好将关键字{{1 }}中的override类)。函数Child是一种机制,可以通过virtual指针调用Child实现。

第二,在Parentx类中都声明变量Parent。这意味着Child对象具有两个名为Child的变量,并且默认情况下x函数中的x将引用{{1}中声明的Child }类(x类中的副本必须是ChildParent才能从public访问,并且由于名称重叠,因此必须通过protected类型指针,或通过像Child中那样显式指定类。