【问题标题】:Does Upcasting in C++ Allow Access to Parent's Private Members or FriendsC++ 中的向上转换是否允许访问父级的私有成员或朋友
【发布时间】:2016-07-03 05:30:45
【问题描述】:

根据我在课堂上学到的知识,派生类不会继承其父类的:

  • 构造函数/析构函数
  • 朋友
  • 私人会员

但是,如果我们将派生类向上转换为它的父类,我们是否可以访问父类的私有成员,并且父类的朋友现在是否可以应用到这个向上转换的类?

我倾向于认为向上转换的派生类将无法访问父类的私有方法和变量,因为派生类首先不继承它们是有原因的。

(以下代码是在验证答案后添加的)

这个c++代码是用来测试我问的问题的:

    #include <iostream>
    class A;
    void funcGetAVal(A);

    class A
    {
        private:

            int aVal;
            friend void ::funcGetAVal(A);
        public:
            A()
            {
                aVal = 0;
            }
    };

    class B : public A
    {
        public:
            int bVal;
            B() : A()
            {
                bVal = 0;
            }
    };

    void funcGetAVal(A aClass)
    {
        std::cout << "A val accessed from friend function: " << aClass.aVal << std::endl;
    }


    int main()
    {
        B * b = new B;
        A * a = new A;
        A * bNowA = reinterpret_cast<A *>(b); //This reinterprets the instance of the derived class into an instance of the base class
        //std::cout << bNowA->aVal << std::endl; //This caused a compile-time error since aVal is a private member of A
        ::funcGetAVal(*a); //This calls the funcGetAVal function with an instance of the base class
        ::funcGetAVal(*bNowA); //This calls the funcGetAVal function with an instance of the derived class reinterpreted as the base class
        //Both funcGetAVal function calls print out 0
        return 0;
    }

结果与 R Sahu 的回答一致。从 B 的实例访问 A 的私有成员导致错误,友元函数能够访问派生类的 aVal。

【问题讨论】:

  • “访问”私有方法和变量是什么意思?无论您如何转换,您都无法访问私有方法和变量。
  • “访问”是指调用函数或将变量与基类一起使用。例如,如果 A 类有一个私有整数:aVal,而 B 类继承了 A,那么如果 B 有一个名为 b 的实例,B 是否可以通过输入 b.aVal 访问 aVal?您的第二句话回答了这个关于私有成员访问的问题。
  • 你误解了一些东西。父类完全包含在派生实例中。仅仅因为属性不可用(通过私有),并不意味着属性不存在。永远不需要向上转换(从派生实例到基础对象),也不建议这样做。请重新阅读教科书中的“is-a”讨论。
  • 我建议您尝试一下...使用“reinterpret_cast”,写一个minimal reproducible example,并告诉我们您遇到了什么问题。
  • 确实,所有的私有变量和方法都会在继承的类中存在,但是你不能直接使用它们,即使你把它上载到父类。这不是因为继承,而是因为函数和变量是私有的。

标签: c++ inheritance friend


【解决方案1】:

但是,如果我们将派生类向上转换为它的父类,我们是否可以访问父类的私有成员

没有。

private 类的成员可以在类的范围内访问。类的成员函数可以访问其私有成员。通过将派生类指针向上转换为不是基类成员函数的函数中的基类指针,您将无法访问基类的private 成员。您只能访问其public 成员。

Parent 类的朋友现在会申请这个向上转换的类吗?

如果将基类的指针传递给基类的friend,则友元函数可以访问基类的privateprotected 成员。

【讨论】:

  • 还可以访问基类的受保护成员,
猜你喜欢
  • 2021-12-30
  • 1970-01-01
  • 1970-01-01
  • 2013-04-09
  • 1970-01-01
  • 2021-08-16
  • 1970-01-01
  • 2023-04-06
  • 2014-06-18
相关资源
最近更新 更多