请先看测试代码:
#include "stdafx.h"
#include <iostream>
using namespace std;
//基类
class Base
{
public:
void get() const;
private:
virtual void dosth() const;
};
void Base::get() const
{
dosth();
}
void Base::dosth() const
{
cout << "Base dosth" << endl;
}
//派生类
class Derived1: public Base
{
public:
virtual void dosth() const;
};
void Derived1::dosth() const
{
cout << "Derived1 dosth" << endl;
}
int _tmain(int argc, _TCHAR* argv[])
{
Base b;
Derived1 d1;
b.get();
d1.get();
//b.dosth();
d1.dosth();
return 0;
}结论是:
1、d1.get()和d1.dosth()能获得相同结果。
2、基类中的private virtual,我们可以在派生类中实现。
3、基类中的private virtual,我们在派生类的public中实现,并不影响它的virtual性。
本文通过一个C++示例程序展示了如何在基类中声明私有的虚函数,并在派生类的公有部分实现该虚函数。实验结果显示,即使基类成员函数为私有,也可以在派生类中正确地覆盖并调用。
541

被折叠的 条评论
为什么被折叠?



