派生类赋值给基类指针,调用成员函数

来源:百度知道 编辑:UC知道 时间:2024/06/23 22:59:45
#include <iostream>
using namespace std;

class A{
public:
int v;
void fun(){ cout<<"Member of A:"<<v<<endl;}

A(){ v=3;cout<<"constructor of A:"<<v<<endl;}
~A(){ cout<<"Delete A:"<<endl;}
};

class B1:virtual public A{
public:
int v;
void fun(){ cout<<"Member of B1:"<<v<<endl;}

B1(){ cout<<"constructor of B1:"<<endl;}
~B1(){ cout<<"Delete B1:"<<endl;}
};

class B2:virtual public A{
public:
int v;
void fun(){ cout<<"Member of B2:"<<v<<endl;}

B2(){ cout<<"constructor of B2:"<<endl;}
~B2(){ cout<<"Delete B2:"<<endl;}

};

class D1: public B2, public B1 {
public:
int v;

要在基类的fun函数上加上 virtual 关键字 应该就可以了.

按照fun的声明,它的信息是不会被记录在类型实例里面的,因此派生出来的类实例化后,实体中并没有foo的相关信息,当然被重定义的fun函数也就不会被调用到了。
而f函数中的所用指针的类型型为A*,所以就会调用A::fun()。
加上virtual就可以得到你想要的结果了。
class A{
// ...
virtual void fun(){ cout<<"Member of A:"<<v<<endl;}
// ....
};