问题描述
我创建了一个抽象基类,它有一个带有默认参数的纯虚方法。
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);
...
}
所以我想知道是好的做法是将默认参数设置为纯virutal和整体虚拟方法?
So I would like to know is it a good practice to set the default argument to pure virutal 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.
这篇关于好pratice:纯虚方法的默认参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!