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()
网友评论