Chu*_*dad 12
访问说明符的应用方式与在名称查找期间对任何其他名称的应用方式相同.功能是虚拟的这一事实根本不重要.
有时会出现与虚函数有关的常见错误.
如果名称查找将可行函数确定为虚函数,则在用于命名函数的对象表达式的静态类型的范围内检查虚函数的访问说明符.在运行时,可以使用完全不同的访问说明符在派生类中定义要调用的实际函数.这是因为"访问说明符"是编译时的现象.
// 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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2475 次 |
| 最近记录: |