私有成员函数外部访问方法


通常私有成员是在类外不能访问的,但是,也有例外的情况。当派生类将基类中的public权限的虚函数(纯虚函数)

重载为private或protected时,可以通过使用基类的指针在外部访问该函数。实例程序如下:

#include <iostream>
using namespace std;
class ANAME
{
public:
	virtual void AddNum() = 0;
};
class BNAME : public ANAME
{
	virtual void AddNum(){cout <<(a+b) <<endl;}
	int a;
	int b;
public:
	void getnum()
	{
		cin >>a >>b;
	}
};
int main()
{
	cout <<"Hello World!" <<endl;
	ANAME* pAname = NULL;
	BNAME* pBname = new BNAME;
	pAname = pBname;
	pBname->getnum();
	cout <<"ANAME指针调用 a+b:" <<endl;
	pAname->AddNum();
//	cout <<"BNAME指针调用 a+b:" <<endl;
	//pBname->AddNum();  //提示私有成员函数 不能在外部访问
	return 0;
}
但这并不是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.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值