多态性:向不同的对象发送同一个消息,不同的对象在接受时会产生不同的行为(即方法)
#include
using namespace std;
class B
{
public:
void print()
{
cout << "B::print()" << endl;
}
virtual void show();
};
void B::show()
{
cout << "B::show()" << endl;
}
class D :public B
{
public:
void print()
{
cout << "B::print()" << endl;
}
void show()
{
cout << "D::show()" << endl;
}
};
class E :public D
{
public:
void show()
{
cout << "E::show()" << endl;
}
};
void fun(B *pb)
{
pb->show();
}
int main()
{
D d;
B b;
E e;
fun(&d);
fun(&b);
fun(&e);
getchar();
return 0;
}
最好把基类的析构函数声明为虚函数
#include
using namespace std;
class B
{
public:
B()
{
cout << "B()" << endl;
}
virtual ~B()
{
cout << "~B()" << endl;
}
};
class D :public B
{
public:
D()
{
cout << "D()" << endl;
}
~D()
{
cout << "~D()" << endl;
}
};
int main()
{
//D d;
B *pb = new D;
delete pb;
getchar();
return 0;
}
新闻标题:多态性与虚函数
转载来源:
http://bzwzjz.com/article/igjphi.html