C++ 纯虚函数也是可以实现的
2019-03-02 本文已影响0人
赵者也
class PureVirtualA {
public:
virtual ~PureVirtualA();
virtual void testPureVirtualFunc() = 0;
protected:
void publicFunc();
};
PureVirtualA::~PureVirtualA()
{
}
void PureVirtualA::publicFunc()
{
std::cout << "PureVirtualA::publicFunc()" << std::endl;
}
void PureVirtualA::testPureVirtualFunc() {
std::cout << "PureVirtualA::testPureVirtualFunc()" << std::endl;
}
class TestB : public PureVirtualA {
public:
void testPureVirtualFunc();
};
void TestB::testPureVirtualFunc() {
PureVirtualA::testPureVirtualFunc();
std::cout << "B::testPureVirtualFunc()" << std::endl;
this->publicFunc();
}
// ... 测试
PureVirtualA* test = new TestB;
test->testPureVirtualFunc();
test->PureVirtualA::testPureVirtualFunc();
默认的实现可以像 publicFunc 一样用于公共的方法来使用
这种方法的好处是少了一个需要维护的函数,缺点是客户代码可以直接调用基类的缺省实现。
// 测试输出:
PureVirtualA::testPureVirtualFunc()
B::testPureVirtualFunc()
PureVirtualA::publicFunc()
PureVirtualA::testPureVirtualFunc()