【问题标题】:Access child member methods from function taking parent class从采用父类的函数访问子成员方法
【发布时间】:2020-03-22 10:46:51
【问题描述】:

测试函数需要接受从Parent 派生的类的任何对象,并访问Function()Child 实现。对我来说,这似乎很容易做到。我尝试执行以下操作。直觉上感觉是对的,但它不起作用。它仍然调用Function()Parent 实现

Class Parent
{
Public:
    Parent();
    ~Parent();

    virtual void Function() = 0;

};

Class Child : public Parent
{
Public:
    Child();
    ~Child();
    void Function(){
        // Do something
    };
};

void Test(Parent Object)
{
    Object.Function();
};

int main()
{
    Child Object;
    Test(Child);
    return 0;
}

如何实现这样的事情?

我错过了什么小东西吗?还是这个解决方案与我想要实现的目标相去甚远?

提前致谢。

【问题讨论】:

  • 请编辑您的问题以显示真实代码。
  • Parent.Function(); 应该是 object.Function(); 并且与 Child 对象相同。请注意,您正在传递 Child 对象的副本,它将被切片。多态行为可以通过指针而不是普通对象来演示。
  • @G.M.真正的代码是什么意思?
  • 抱歉,您是否尝试过编译代码,如图所示。正如我所说,您提供的代码是真实代码,这一点很重要。

标签: c++ inheritance polymer member-functions


【解决方案1】:

要在 C++ 中使用虚函数,您必须使用引用或指针。试试这个

void Test(Parent& Object) // reference to Parent
{
    Object.Function();
};

您应该研究object slicing 以了解您的版本出了什么问题,以及为什么必须使用引用或指针。

【讨论】:

  • 一个错字:Object.Function()
猜你喜欢
  • 2014-07-13
  • 2018-09-24
  • 1970-01-01
  • 1970-01-01
  • 2018-07-22
  • 2012-10-08
  • 2011-11-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多