对虚函数的访问
适用于虚函数的访问控制由用于进行函数调用的类型决定。 重写函数的声明不会影响给定类型的访问控制。 例如:
// access_to_virtual_functions.cpp
class VFuncBase
{
public:
virtual int GetState() { return _state; }
protected:
int _state;
};
class VFuncDerived : public VFuncBase
{
private:
int GetState() { return _state; }
};
int main()
{
VFuncDerived vfd; // Object of derived type.
VFuncBase *pvfb = &vfd; // Pointer to base type.
VFuncDerived *pvfd = &vfd; // Pointer to derived type.
int State;
State = pvfb->GetState(); // GetState is public.
State = pvfd->GetState(); // C2248 error expected; GetState is private;
}
在前面的示例中,使用指向 VFuncBase 类型的指针调用虚函数 GetState 将调用 VFuncDerived::GetState,并且会将 GetState 视为公共的。 但是,使用指向 VFuncDerived 类型的指针调用 GetState 是访问控制冲突,因为在 VFuncDerived 类中将 GetState 声明为私有的。
警告
可以使用指向基类 VFuncBase 的指针调用虚函数 GetState。这并不意味着调用的函数是该函数的基类版本。