良好做法:纯虚方法的默认参数 [英] Good practice : Default arguments for pure virtual method
问题描述
我创建了一个抽象基类,该基类具有带默认参数的纯虚拟方法.
I have created an abstract base class, which has a pure virtual method with default argument.
class Base {
...
virtual someMethod(const SomeStruct& t = 0) = 0;
...
}
class Derived : public Base {
...
virtual someMethod(const SomeStruct& t = 0);
...
}
所以我想知道将默认参数设置为纯虚拟方法并将整体参数设置为虚拟方法是一种好习惯吗?
So I would like to know is it a good practice to set the default argument to pure virtual and overall to virtual methods?
推荐答案
我经常希望同时使用默认参数和虚函数.其他人正确地指出,这会导致模棱两可,通常不是一个好主意.有一个相当简单的解决方案,我可以使用.给虚拟函数起一个不同的名称,使其受保护,然后为公用函数提供调用它的默认参数.
I often wish to use both default parameters and virtual function as you do. The others have rightfully pointed out however that this leads to ambiguity and is generally not a good idea. There is a reasonably simple solution, one that I use. Give your virtual function a different name, make it protected, and then provide a public function with default parameters which calls it.
class Base {
protected:
virtual void vSomeMethod(const SomeStruct& t ) = 0;
public:
void someMethod( const SomeStruc& t = 0 )
{ vSomeMethod( t ); }
}
派生类仅覆盖 vSomeMethod
,而不必担心默认参数.
Derived classes simply override vSomeMethod
and don't worry at all about the default parameters.
这篇关于良好做法:纯虚方法的默认参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!