从父级调用派生的 class 重写函数。 C++

Calling derived class overriden function from parent. C++

我有一个父 class P,派生 class D,并且它们都有函数 show() 。此外,我有一个 P 对象数组,在该数组中我正在分配从 P 派生的对象,如 D。我正在从数组调用 show() 函数。但是好像只调用了P空函数,没有派生覆盖函数。

我的代码:

//parent.h    

class P
{
public:
    P(){ }
    ~P(){ }

    virtual void show(){ }
};

//derived.h

#include "parent.h"

class D : public P
{
public:
    D(){ }
    ~D(){ }

    void show();
};

//derived.cpp

#include "derived.h"

void D::show()
{
    std::cout<<"Showing Derived Function\n";
}

//main.cpp

#include "derived.h"
#include <vector>

int main()
{
    vector<P> objectz;

    for(int i=0; i<8; i++)
    {
        D derp;
        objectz.insert(objectz.begin(), derp);
    }

    for(int i=0; i<8; i++)
    {
        objectz[i].show(); //Call it Here !!
    }

    return 0;
}

这可能是因为您没有将数组声明为 P 指针数组。确保您的数组声明如下:

P* elements[ N ];

下面是一些显示多态性的示例代码:

#include <iostream>
#include <cstddef>

struct P
{
    virtual void func() { std::cout << "Parent" << std::endl; }
};

struct D : P
{
    void func() override { std::cout << "Derived" << std::endl; }
};

int main()
{
    const std::size_t N( 2 );

    P* elements[ N ];

    P parent;
    D derived;

    elements[ 0 ] = &parent;
    elements[ 1 ] = &derived;

    for ( std::size_t i( 0 ); i < N; ++i )
        elements[ i ]->func();

    std::cout << "Enter a character to exit: "; char c; std::cin >> c;
    return 0;
}

使用std::vector:

#include <iostream>
#include <cstddef>
#include <vector>

... // same P and D definitions as in the previous example.

int main()
{
    std::vector<P*> elements; 

    elements.push_back( &P() ); // &P(): create an instance of P and return its address.
    elements.push_back( &D() ); // &D(): create an instance of D and return its address.

    for ( std::vector<P*>::size_type i( 0 ), sz( elements.size() ); i < sz; ++i )
        elements[ i ]->func();

    std::cout << "Enter a character to exit: "; char c; std::cin >> c;
    return 0;
}