private成员函数竟然可以在类的外部调用

今天写代码竟然发现,private成员函数竟然可以在类的外部调用,开始以为是C++设计的缺陷。但是逐步深入才知道C++多态的博大精深。

#include <iostream>

using namespace std; 
class Base
{
public:
	virtual void Func()
	{
		cout<<"base"<<endl;
	}
};

class Derived : public Base
{
private:
	void Func()	
	{
		cout<<"derived"<< endl;
	}
};


int main()
{
	Base *d = new Derived;
	d->Func( );
	delete d;
	
	return 0;
}

查看了一下资料,发下了下面的内容,这下一下子就明了了。

/*参考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.

*/
    我们知道 C++ 多态的包括编译时多态和运行时多态,而通过基类的指针或者引用调用虚函数时,会发生动态的绑定,而编译器的处理是静态的,它只会在调用该成员函数的时候,在当前类的作用域中进行访问控制检查( Base 类或者 B 类中 f 函数是 public , 因此可以通过编译器的检查),而对 C++ 运行过程中的动态绑定 ( 由于使用了基类的指针调用虚函数,程序运行时动态执行了子类的函数 f()) 是不为所知,也就出现了上面的那段代码,外部直接调用了 Derived 的私有函数成员,而编译器却不为所知。

    我们可以想像:当一个子类的虚成员函数通过基类的指针调用时,访问权限取决于基类对该函数的声明,而C++privateproected仅仅是一个访问限定符,它只限定函数和数据不能被“直接”访问,而不担保这些函数和数据会被通过其他方法间接地访问到,在成员函数中返回一个类私有数据成员的引用,在外部就可以对这个私有属性进行修改(这个请参照博主的另一篇博客,对这个现象有说明)也是这个道理。

  • 6
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值