码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2014-12-22 22:35:45      阅读:315      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!