通常私有成员是在类外不能访问的,但是,也有例外的情况。当派生类将基类中的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.