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


#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

原因:

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


相关文章:

  • 2021-08-26
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-05-26
  • 2021-08-14
  • 2021-11-06
  • 2021-11-13
  • 2021-09-06
  • 2021-06-29
  • 2022-02-27
相关资源
相似解决方案