虚函数实现多态性的三个步骤

虚函数实现多态性的三个步骤

1、在基类中将需要多态调用的成员函数声明为virtual。

2、在派生类中覆盖基类的虚函数,实现各自需要的功能。

3、用基类的指针或者引用指向派生类对象,通过基类指针或者引用调用虚函数。

注:在派生类中把覆盖的成员函数设置成私有成员函数一样可以调用。

#include

#include

#include

using namespace std;

class base{

public:

base(string _name = "NULL"):name(_name){}

virtual string GetName(){return name;}

virtual void Print(){cout<

virtual ~base(){}

private:

string name;

};

class derived:public base

{

public:

derived(string _name = "NULL",int _val = 0):base(_name),val(_val){}

string GetName(){return base::GetName();}

virtual ~derived(){}

private:

int val;

void Print(){base::Print();cout<<" "<

};

int main()

{

base a("base");

base *pa = &a;

base &ya = a;

derived b("derived",8);

base *pb = &b;

base &yb = b;

pa->Print();

cout<

ya.Print();

cout<

pb->Print();

cout<

yb.Print();

cout<

system("PAUSE");

return 0;

}

相关文章