读程序,写出输出的结果:
关于虚函数和多态,可参考一篇不错的文章http://blog.youkuaiyun.com/moxiaomomo/article/details/6826412
1、virtual意味着运行时再决定调用哪个函数。
#include<iostream>
using namespace std;
class Base
{
public:
Base(){}
virtual ~Base(){}
void func1(){
cout << "func1 in base~" << endl;
func2();
}
virtual void func2(){
cout<<"func2 in base~"<<endl;
}
};
class Derive: public Base
{
public:
Derive(){}
~Derive(){}
void func1(){
cout<<"func1 in Derive~"<<endl;
func2();
}
void func2(){
cout<<"func2 in Derive~"<<endl;
}
};
int main()
{
Derive d;
Base* b=&d;
b->func1();
return 0;
}

2、当通过基类的指针删除派生类的对象,而基类又没有虚析构函数时,结果将是不确定的。实际运行时经常发生的是,派生类的析构函数永远不会被调用,那么派生类的资源也将无法释放。
#include<iostream>
using namespace std;
class base
{
public:
base(){cout << "construct in base" << endl;};
~base() {cout << "disconstruct in base" << endl;};
};
class derive: public base
{
public:
derive();
~derive();
private:
char *buf;
};
derive::derive() {
buf = (char *)malloc(100);
cout << "cosntruct in derive" << endl;
}
derive::~derive() {
if(buf)
delete buf;
cout << "disconstruct in derive" << endl;
}
int main()
{
base *pa = new derive();
delete pa;
return 0;
}
