C++虚函数带有默认参数的问题

此问题在Effective C++ 条款38: 决不要重新定义继承而来的缺省参数值中有描述

例:

#include <iostream>
#include <string>
//using namespace std;
class Base
{
public:
    virtual void display(const std::string& strShow = "I am Base class !")
    {
        std::cout << strShow << std::endl;
  std::cout << "Base display" << std::endl;
    }
    virtual ~Base(){}
};


class Derive: public Base
{
public:
    virtual void display(const std::string& strShow  = "I am Derive class !")
    {
        std::cout << strShow << std::endl; 
  std::cout << "Derive display" << std::endl;
    }
    virtual ~Derive(){}
};
int main()
{
    Base* pBase = new Derive();
    Derive* pDerive = new Derive();
    pBase->display();  
    pDerive->display();
    delete pBase;
    delete pDerive;
    getchar();
    return 0;
}
 
 

 结果:


I am Base class !

Derive display

I am Derive class!

Derive display


解析:

因为虚函数和默认参数的绑定方式不同

虚函数为动态绑定,而默认参数静态绑定。

在使用父类指针指向的对象调用虚函数时,函数会按实际指向的对象调用对应的成员函数(动态绑定的结果),

而函数的默认参数依旧为父类对象中的默认参数(静态绑定的结果)。

如例所示,调用的方法不同,而输出的默认参数值相同。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值