重载overload和重写override均是多态的一种!
虚函数属于重写的范畴!
但是,如果重载了虚函数会怎样呢?
#include <iostream> #include <string> #include <memory>
#define str(f) #f
void printLine(std::string s) { std::cout<<s<<std::endl; }
class A { public: virtual void vfun(int) { printLine(str(vfun in A)); } void fun(int) { printLine(str(fun in A)); } };
class B : public A { public: void vfun(double) { printLine(str(vfun in B));} };
int main() { std::auto_ptr<A> pb(new B); pb->fun(1); pb->vfun(1.0); // 1 warning
pb->vfun(1); system("pause"); return 0; }
|
输出结果:
fun in A vfun in A vfun in A
|
可见,如果通过指向基类的指针,而该指针实际指向一个子类,调用虚函数时,而子类重载了该虚函数,则实际调用的仍是基类中的虚函数。(自顶向下,基类隐藏了子类)
修改一下上面的main函数:
int main() { std::auto_ptr<B> pb(new B); pb->fun(1); pb->vfun(1.0); pb->vfun(1); system("pause"); return 0; }
|
输出结果:
fun in A vfun in B vfun in B
|
可见,如果通过指向子类的指针,调用虚函数,而子类重载了该虚函数,则实际调用的将是子类中的虚函数。(自下向上,子类隐藏了基类的虚函数)
即使子类重载了基类中的虚函数,还是可以让基类中虚函数在子类中存在的:
#include <iostream> #include <string> #include <memory>
#define str(f) #f
void printLine(std::string s) { std::cout<<s<<std::endl; }
class A { public: virtual void vfun(int) { printLine(str(vfun in A)); } void fun(int) { printLine(str(fun in A)); } };
class B : public A { public: using A::vfun; // newly added
void vfun(double) { printLine(str(vfun in B));} };
int main() { std::auto_ptr<B> pb(new B); pb->fun(1); pb->vfun(1.0); pb->vfun(1); system("pause"); return 0; }
|
输出结果:
fun in A vfun in B vfun in A
|
阅读(945) | 评论(2) | 转发(0) |