在C ++中提供对派生类的更严格访问 [英] Providing more strict access to derived class in C++

查看:75
本文介绍了在C ++中提供对派生类的更严格访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Hi everyone i have one question is my mind

This program worked
-----------------------------------------
#include<iostream>
using namespace std;
//declaring base class
class Base {
public:
    virtual int fun(int i) { cout << "Base::fun(int i) called"; }
};
//Declaring Derived class
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;
}

//It worked and gave output as :
Derived::fun(int x) called

But the below program didn't worked, don't know why
-------------------------------------------------
#include<iostream>
using namespace std;
//Declaring base class
class Base {
private:
    virtual int fun(int i) { cout << "Base::fun(int i) called"; }
};
//Declaring Derived class
class Derived: public Base {
public:
    int fun(int x)   { cout << "Derived::fun(int x) called"; }
};
int main()
{
    Base *ptr = new Derived;
    ptr->fun(10);
    return 0;
}





我尝试过:



我已经学习了虚函数,但在以上两个程序中遇到了困惑



What I have tried:

I have learnt virtual functions but got confused in above two programs working

推荐答案

第二个版本会产生编译错误。编译器看到对 Base :: fun()的访问权限被拒绝,因为这是私有的。



In第一个版本是允许的,因为 Base :: fun()是公开的。因为该函数是虚函数,所以编译器不会生成直接调用函数代码的代码,而是使用对象的vtable(动态调度)。由于该对象的类型为 Derived ,因此vtable将在运行时指向 Derived :: fun()被称为。 vtable不知道调度函数的可访问性,因此即使将有效调用的函数声明为private也是如此。
The second version will generate a compiler error. The compiler sees an access to Base::fun() which is denied because that is private.

In the first version it is allowed because the Base::fun() is public. Because the function is virtual, the compiler will not generate code to call the function code directly but to use the vtable of the object (dynamic dispatch). Because the object is of type Derived, the vtable will point to Derived::fun() at run-time and that is called. The vtable does not know about the accessibility of the dispatched function and so it works even when the effectively called function is declared as private.


这篇关于在C ++中提供对派生类的更严格访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆