访问说明符和虚函数

Alo*_*ave 2 c++ virtual

在C++指定的3个不同访问说明符(公共,私有,受保护)下声明虚函数时,可访问性的规则是什么?每个访问说明符的含义是什么?任何解释这个概念的简单代码示例都非常有用.

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)