Effective C++ .37 virtual函数中默认参数的表现

#include <iostream>
#include <cstdlib>

using namespace std;

class Pen {
public:
    virtual void write(int color = 0) {
        cout<<"write with color:"<<color<<endl;
    }
};

class Pencil : public Pen{
public:
    void write(int color = 128) {
        cout<<"write with color:"<<color<<endl;
    }
};

int main() {
    
    Pen* p = new Pencil();
    
    p->write();
    
    return 0;
}

输出:

write with color:0

 

即虚函数,执行那个函数是运行时决定的,但是其默认参数却是静态决定的,用了什么类型的指针就使用哪套默认参数。

 

因而最好不要再virtual函数中出现默认参数

posted @ 2014-12-22 21:17  卖程序的小歪  阅读(275)  评论(0编辑  收藏  举报