Jon*_*ter 10 c++ abstract-class
在C++中是否有一种方法可以编写一个具体的类,当另一个类派生它时,它有一个必须重写的方法.抽象类允许强制派生类创建任何抽象方法的具体版本,但我想要的是一个强制执行此操作的基类,但也可以单独使用它.我知道抽象方法也可以指定默认功能,但这仍然是一个无法实例化的抽象类.
我也查看了模板方法模式,但这似乎并不是我正在寻找的.
我假设您正在寻找编译时强制执行此条件的方法(感谢@Chad 指出这一点)
据我所知,C++ 中没有直接的语言机制。我的意思是,在方法声明前面没有保留关键字可以实现您的预期目标。
我认为你所说的是指向你的软件中的设计问题。假设您想强制 foo() 方法由以下代码片段中的所有继承类重新实现
class BaseButConcrete
{
... //Common stuff
... //
virtual void foo()
{ /*implementation that you do not want to be inherited, but will be...*/ }
}
class DerivedOtherConcrete : public BaseButConcrete
{
void foo()
{ /*different implementation,
but no obligation from compiler point of view*/ }
}
Run Code Online (Sandbox Code Playgroud)
我看不出为什么所有常见的东西不能在抽象基类中移动,这没有什么好的设计原因。根据您的描述,您不想继承Derived 中的foo实现,因此不要继承该部分!因此,非常经典的设计应该可以达到目的:
class AbstractBase
{
... //Common stuff has moved here
... //
virtual void foo() =0;
}
class NotAnymoreBaseButStillConcrete : public AbstractBase
{
void foo()
{ /*implementation that should not be inherited,
and that will not by design*/ }
}
class DerivedOtherConcrete : public AbstractBase
{
void foo()
{ /*different implementation,
now mandatory compiler-wise for the class to be concrete*/ }
}
Run Code Online (Sandbox Code Playgroud)
这样,公共内容仍然在所有派生类之间共享,并且您可以将不想继承的内容(即 foo实现)分隔在不在同一继承路径上的类中。
| 归档时间: |
|
| 查看次数: |
5789 次 |
| 最近记录: |