c++有趣现象:private的成员函数可以在类的外部调用

 我来答
大沈他次苹0B
2015-10-27 · TA获得超过7144个赞
知道大有可为答主
回答量:3059
采纳率:100%
帮助的人:153万
展开全部
它并不是C++的缺陷或是被设计者所忽视的问题。

当我们使用虚函数的时候,它的访问规则是在声明的时候被确定的,而不是在被“子类重写”(overridden)的时候,虚函数的访问规则不会受到来自被重写的子类函数的影响,更进一步说,当某个对象A的引用B(特指间接访问)用来调用该对象的虚函数时,对于该对象A的一切声明信息,都取决于该对象的引用B,而不是这个引用所引用的对象A。

C++标准里有对该问题的具体说明:当一个子类函数通过基类的指针调用时,访问权限取决于基类对该函数的声明。

参考C++ Standard ISO/IEC 14882:2003(E) 第11.6节:

11.6 Access to virtual functions [class.access.virt]

The access rules (clause 11) for a virtual function are determined by its declaration and are not affected by the rules for a function that later overrides it. [Example:
class B {
public:
virtual int f();
};
class D : public B {
private:
int f();
};
void f()
{
D d;
B* pb = &d;
D* pd = &d;
pb->f(); //OK: B::f() is public,
// D::f() is invoked
pd->f(); //error: D::f() is private
}
—end example]

Access is checked at the call point using the type of the expression used to denote the object for which the member function is called (B* in the example above). The access of the member function in the class in which it was defined (D in the example above) is in general not known.

至少我们在程序编译时无法获知这个指针的值,它会指向何种位置。

经验:private仅仅是一个访问限定符,它只限定函数和数据不能被“直接”访问,而不担保这些函数和数据会被通过其他方法间接地访问到,在成员函数中返回一个类私有数据成员的引用也是这个道理。
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式