LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 156|回复: 0

对虚函数的访问

[复制链接]
发表于 2024-2-2 23:11:38 | 显示全部楼层 |阅读模式
适用于 virtual 函数的访问控制是由用于进行函数调用的类型决定的。 重写函数的声明不会影响给定类型的访问控制。 例如:

// 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 视为 public。 但是,使用指向 VFuncDerived 类型的指针调用 GetState 是一种访问控制冲突,因为 GetState 在 VFuncDerived 类中被声明为 private。

注意

可以使用指向基类 GetState 的指针调用虚函数 VFuncBase。 这并不意味着调用的函数是该函数的基类版本。

您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表