问题
I'm writing some code using a simple clone pattern, I'd like it if I were able to force derived classes to override that clone pattern, but retain the ability to use my base class. (So I don't want to declare the clone method to be pure virtual.)
Is there anyway to enforce this restriction at the compiler level?
回答1:
Unfortunately there is just no way to make this happen in C++. You can't force a non-abstract method to be overridden in child classes. However, I might note that concrete base classes should be fairly rare in C++ and you might want to reconsider your design. With more information about your overall aims we might be able to provide a better answer for your precise needs.
回答2:
It has been some time I touched C++, but I do remember you can have pure virtual method with body.
// in header
class YourBase {
public:
virtual Foo bar() = 0;
};
// in source
Foo YourBase::bar() {
// a default impl
}
That should force the child class to override bar(), while leaving a usable impl of bar() in YourBase
回答3:
Unfortunately you can't enforce at compile time that a class overrides a method of a concrete base class, but you can simply assert
in each clone
function implementation that the type is the type of the class where that implementation resides,
assert( typeid( *this ) == typeid( ThisClass ) );
and then run a test that exercises the cloning functionality of every class.
来源:https://stackoverflow.com/questions/12632747/forcing-a-derived-class-to-overload-a-virtual-method-in-a-non-abstract-base-clas