C++虚函数相关内容

样例代码

class Base
{
public:
Base(){};
virtual ~Base(){    //若没有设置为虚函数:如果有这样的指针Base *p=new Derived();声明,则在delete p时不能调用Derived析构,会出现泄漏。
cout << "Base" << endl;
};
virtual void DoSomething(){ //若不为虚函数:则同上,父类指针不能使用子类里面的DoSomething()方法
cout << "Do Base!" << endl;
};
};
class Derived :public Base{
public:
Derived(){};
~Derived(){
cout << "Derived!" << endl;
}
void DoSomething(){
cout << "Do Derived!" << endl;
}
void f(){             //该函数只有在子类指针中调用
cout << "Hello!" << endl;
}
};

总结:虚函数最直观的解释就是,让父类能够使用子类的方法(这种使用方式可以类比为继承的反用法)。

posted @ 2016-04-08 10:40  busman  阅读(148)  评论(0编辑  收藏  举报