有默认参数的虚函数

来源:互联网 发布:淘宝怎样申请部分退款 编辑:程序博客网 时间:2024/05/22 11:55

《Effective C++》条款37:绝不重新定义继承来的缺省参数值

虚函数是动态绑定,而default参数是静态绑定,在编译期就已经确实能够。
以下是说明代码:

#include <cstdio>#include <iostream>#include <string>using namespace std;class Parent{public:    virtual void prints(const string& str = "Parent!")    {        cout << str << endl;    }};class Child :public Parent{public:    virtual void prints(const string& str = "Child!")    {        cout << str << endl;    }};class GrandChild:public Child{public:    virtual void prints(const string& str = "GrandChild!")    {        cout << str << endl;    }};int main(){    Parent* p = new GrandChild;    Child* c = new GrandChild;    GrandChild* gc = new GrandChild;    p->prints();    c->prints();    gc->prints();    system("pause");    return 0;}

输出:这里写图片描述

从输出结果可以看出,虽然prints()是虚函数,派生类都对它进行了重写,但是在没给出新的参数时,即使父类指针指向的对象是派生类,默认参数也是以父类指针为准,而且是由父类指针的类型决定,不同指针类型采用不同默认参数。由此可见,虽然虚函数是动态绑定,但是缺省参数值是静态绑定,在编译期就已经确定。

而c++为什么会坚持这种看似不合常理的机制那?
原因是:运行期效率。如果缺省参数值是动态绑定,编译器就必须有某种办法在运行期为虚函数决定合适的缺省参数值,这比目前实行的在编译期决定缺省参数值的机制要慢而且复杂。为了程序的执行速度和编译器复杂度,c++做了取舍。

0 0
原创粉丝点击