当虚拟函数在 C++ 指定的 3 种不同的访问说明符(public、private、protected)下声明时,可访问性规则是什么
每一个的意义是什么?任何解释该概念的简单代码示例都将非常有用。
访问说明符的应用方式与在名称查找期间应用于任何其他名称的方式相同。该函数是虚拟的这一事实根本不重要。
关于虚函数,有时会发生一个常见的错误。
如果名称查找确定可行函数是虚函数,则在用于命名该函数的对象表达式的静态类型范围内检查该虚函数的访问说明符。在运行时,要调用的实际函数可以使用完全不同的访问说明符在派生类中定义。这是因为“访问说明符”是一种编译时现象。
// Brain compiled code ahead
struct A{
virtual void f() {}
private:
virtual void g() {}
protected:
virtual void h() {}
};
struct B : A{
private:
virtual void f() {} // Allowed, but not a good habit I guess!
};
B b;
A &ra = b;
ra.f(); // name lookup of 'f' is done in 'A' and found to be public. Compilation
// succeeds and the call is dynamically bound
// At run time the actual function to be called is 'B::f' which could be private, protected etc but that does not matter
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)