Effective C++ 学习笔记(23)

决不要重新定义继承而来的缺省参数值


#include <iostream>
using namespace std;

enum color
{
RED,GREEN,BLACK,WHITE
};
class Base
{
public:
virtual void ShowColor(color myColor = BLACK)
{
cout
<<"Base Color is "<<myColor<<endl;
}
};

class Derived:public Base
{
public:
virtual void ShowColor(color myColor = RED)
{
cout
<<"Derived Color is "<<myColor<<endl;
}
};
int main()
{
Base
* B = new Derived;
B
->ShowColor();
return 0;
}

  

运行结果:

Derived Color is 2

原因:

虚函数是动态绑定而缺省参数值是静态绑定的。


原文地址:https://www.cnblogs.com/DanielZheng/p/2129949.html