带参数虚函数

引用一句话:
Effective C++ 条款38: 决不要重新定义继承而来的缺省参数值
因为虚函数和默认参数的绑定方式不同,当父类的指针调用子类的虚函数时,采用的参数还是子类虚函数中参数。
具体来说就是如果虚函数中含有参数,虚函数为动态绑定,而默认参数静态绑定。
在使用父类指针指向的对象调用虚函数时,函数会按实际指向的对象调用对应的成员函数(动态绑定的结果),
而函数的默认参数依旧为父类对象中的默认参数(静态绑定的结果)。
例子:

#include <iostream>

using namespace std;
class Base
{
public:
virtual void Display(const std::string &strShow = "Base class !")
    {
    std::cout <<"Base class !" << std::endl;
    std::cout <<"strShow:" << strShow<<std::endl;
    }
};
class Derive: public Base
{
    public:
    virtual void Display(const std::string &strShow = "Derive class !")
    {
    std::cout << "Derive class !";
    std::cout <<"strShow:" << strShow<<std::endl;
    }
};
int main()
{
    Base *pBase = new Derive();
    Derive *pDerive = new Derive();
    pBase->Display(); // 程序输出: Base class ! 而期望输出:Derive class !
    pDerive->Display(); // 程序输出: Derive class !
    return 0;
}

输出:
Derive class !strShow:Base class !
Derive class !strShow:Derive class !
说明:即子类的虚函数被调用了两次,但是pBase->Display()时使用的参数时父类的默认参数,但是实际调用的还是子类的虚函数

原文地址:https://www.cnblogs.com/zhaobinyouth/p/15396952.html