C++ 派生类方法的默认参数的最佳实践

C++ 派生类方法的默认参数的最佳实践,c++,C++,我知道以下内容在VC++12上有效,所以我一直在做: class IBase { virtual void Method(int param = 0) = 0; // default here } class Derived { void Method(int param = 0); // default here } void Derived::Method(int param /*= 0*/) // no default here { // do something } 标

我知道以下内容在VC++12上有效,所以我一直在做:

class IBase
{
  virtual void Method(int param = 0) = 0; // default here
}

class Derived
{
  void Method(int param = 0); // default here
}

void Derived::Method(int param /*= 0*/) // no default here
{
  // do something
}

标准、最佳实践或经验是否推荐了另一种方法,还是可以?默认值应该只在接口类/派生类中,还是两者都在?为什么呢?

最佳做法是将默认参数放在声明(头文件)和源文件中——忘记默认参数。你这样做是正确的。这样,此函数的所有用户都可以看到默认参数,并且可以选择不提供默认参数

如果将默认参数放入定义中,则使用默认参数的所有其他翻译单元(表示不提供默认参数)将导致编译错误

从继承的角度来看,默认值不会保留。使用的默认值来自用于调用函数的指针类型(基指针或派生指针)。因此,它实际上可以归结为您的用例