访问说明符和虚函数 [英] Access specifiers and virtual functions

查看:54
本文介绍了访问说明符和虚函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

What are the rules for accessibility when virtual functions are declared under 3 different access specifiers specified by C++(public, private, protected) What is the significance of each? Any simple code examples to explain the concept will be highly useful.

推荐答案

访问说明符的使用方式与在名称查找过程中对任何其他名称的使用方式相同.该功能是虚拟的这一事实根本无关紧要.

Access specifiers apply in the same way as they would to any other name during name lookup. The fact that the function is virtual does not matter at all.

对于虚函数有时会发生一个常见错误.

There is a common mistake which sometimes happens with respect to virtual functions.

如果名称查找确定可行的功能为虚拟功能,则在用于命名功能的对象表达式的静态类型的范围内检查虚拟功能的访问说明符.在运行时,可以在派生类中使用完全不同的访问说明符定义要调用的实际函数.这是因为访问说明符"是编译时现象.

If name lookup determines a viable function to be a virtual function, the access specifier of the virtual function is checked in the scope of the static type of the object expression used to name the function. At run time, the actual function to be called could be defined in the derived class with a completely different access specifier. This is because 'access specifiers' are a compile time phenomonon.

// 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

这篇关于访问说明符和虚函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆