在C ++中,是否有可能要求基类中的方法被其所有派生类覆盖,而无需使其成为纯虚方法?
#include <iostream>
using namespace std;
class BaseClass{
public:
int printStuff(){ //find some way to require all derived classes to override this method
cout << "Printing some stuff";
}
};
class DerivedClass: public BaseClass{
};
int main(){
cout << "Hello World!";
return 0;
}
最佳答案
我知道您说过您不想使用纯虚函数,但是您可以使用纯虚函数,并且仍然要为方法提供一个定义(如果您要这样做的话)(不确定您是否已经知道):
class BaseClass{
public:
virtual int printStuff() = 0;
};
// give the pure virtual function an implementation
int BaseClass::printStuff() {
cout << "Printing some stuff";
}
class DerivedClass: public BaseClass{
// compiler error; DerivedClass must override printStuff
};
class DerivedClass2: public BaseClass{
public:
int printStuff() {
return BaseClass::printStuff(); // use the base class's implementation
}
};
关于c++ - 要求基类中的方法被其所有子类覆盖,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11066457/