首页 > 编程语言 > 详细

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

时间:2014-12-22 22:34:12      阅读:392      评论:0      收藏:0      [点我收藏+]
#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函数中出现默认参数

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

原文:http://www.cnblogs.com/lailailai/p/4179003.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!