我有两个父类P,派生类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;
}
答案 0 :(得分:2)
这可能是因为您没有将数组声明为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;
}