标签:
virtual 函数会动态绑定,而virtual函数的缺省参数值是静态绑定的。用一个base类型的指针p去指向一个derived类对象,通过p调用虚函数时,会动态绑定到实际所指对象中的函数;用一个derived类型的指针p2指向一个derived对象,由p2调用函数时,直接就是调用的derived中的函数,其参数值也是derived类中函数对应的参数值。
#include <iostream> using namespace std; class A { public: enum Color {red,green,blue}; A() { cout<<"Construct A"<<endl; } virtual void dodraw() { draw(); } private: virtual void draw(Color color=blue) const { cout<<"base draw:"<<color<<endl; } }; class B:public A { public: B() { cout<<"Construct B"<<endl; } virtual void dodraw() { draw(); } private: virtual void draw(Color color=red) const { cout<<"derived draw:"<<color<<endl; } }; int main() { B b; A *p=&b; B *p2=&b; p->dodraw(); p2->dodraw(); return 0; }
上面的程序中,在B类中都重写了A中的两个virtual函数,从而,通过p和p2调用dodraw函数,其实都是调用的B中dodraw,而B中的dodraw函数调用B中draw函数,从而draw的实参就是B中的缺省实参:red
#include <iostream> using namespace std; class A { public: enum Color {red,green,blue}; A() { cout<<"Construct A"<<endl; } virtual void dodraw() { draw(); } private: virtual void draw(Color color=blue) const { cout<<"base draw:"<<color<<endl; } }; class B:public A { public: B() { cout<<"Construct B"<<endl; } private: virtual void draw(Color color=red) const { cout<<"derived draw:"<<color<<endl; } }; int main() { B b; A *p=&b; B *p2=&b; p->dodraw(); p2->dodraw(); return 0; }
effective C++中条款37:绝不重新定义继承而来的缺省参数值
标签:
原文地址:http://blog.csdn.net/yinqiaohua/article/details/46633815