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

来源:互联网 发布:windows怎么打开pages 编辑:程序博客网 时间:2024/05/16 17:04

此问题在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


解析:

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

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

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

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

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


0 0
原创粉丝点击