当C++中派生类方法受到更严格的访问时会发生什么?

我们在Java中讨论了一个类似的主题 在这里 与java不同,C++允许对派生类方法给予更严格的访问。例如,下面的程序编译得很好。

null

C++

#include<iostream>
using namespace std;
class Base {
public :
virtual int fun( int i) { }
};
class Derived: public Base {
private :
int fun( int x)   {  }
};
int main()
{  }


在上面的程序中,如果我们将main()改为following,将得到编译器错误,因为fun()在派生类中是私有的。

C++

int main()
{
Derived d;
d.fun(1);
return 0;
}


下面的节目呢?

C++

#include<iostream>
using namespace std;
class Base {
public :
virtual int fun( int i) { cout << "Base::fun(int i) called" ; }
};
class Derived: public Base {
private :
int fun( int x)   { cout << "Derived::fun(int x) called" ; }
};
int main()
{
Base *ptr = new Derived;
ptr->fun(10);
return 0;
}


输出:

 Derived::fun(int x) called 

在上面的程序中,通过基类指针调用私有函数“Derived::fun(int)”,程序运行良好,因为fun()在基类中是公共的。在编译时检查访问说明符,fun()在基类中是公共的。在运行时,只调用与所指向对象对应的函数,不检查访问说明符。因此,派生类的私有函数是通过基类的指针调用的。 如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写评论

© 版权声明
THE END
喜欢就支持一下吧
点赞8 分享