代码之家  ›  专栏  ›  技术社区  ›  powerpete

作为基类的类型传递参数时,访问基类的受保护成员[重复]

  •  0
  • powerpete  · 技术社区  · 5 年前

    以下代码生成编译器错误:

    “basetest::\u protmember”:无法访问在中声明的受保护成员 “基本测试”类

    为什么我不能访问成员变量 _protMember 在我的 class SubTest 即使它受到保护?

    class BaseTest
    {
    public:
        BaseTest(){};
    
        BaseTest(int prot)
        {
            _protMember = prot;
        };
    
    protected:
        int _protMember;
    };
    
    class SubTest : public BaseTest
    {
        // followup question
        SubTest(const SubTest &subTest)
        {
            _protMember = subTest._protMember; // this line compiles without error
        };
    
        SubTest(const BaseTest &baseTest)
        {
            _protMember = baseTest._protMember; // this line produces the error
        };
    };
    

    后续问题:

    为什么在添加的复制构造函数中 我可以访问受保护的成员 另一个例子?

    0 回复  |  直到 11 年前
        1
  •  11
  •   Tony Delroy    11 年前

    你只能访问 protected 来自您自己的基类实例的成员…没有一个作为参数提供给您。这都是关于oo封装的。如果没有这个限制,正在构造的对象可能会使 baseTest& 参数。

    换个角度,你的 SubTest 可以决定 受保护的 与另一个成员对同一个成员的用法冲突的成员 BaseTest -派生类(例如 SubTest2 : BaseTest )如果你 子测验 代码被允许篡改另一个对象的数据,它可以使A中的不变量无效。 SubTest2 对象,或从中获取某些值,这些值在预期的封装中只应暴露给 子测试2 和(可选-见下文) 子测试2 衍生工具。

    后续问题: 为什么,在添加副本构造函数中,我可以访问另一个实例的受保护成员?

    SubTest(const SubTest& x);  // can access x._protMember
    SubTest(const BaseTest& x);  // cannot access x._protMember
    

    上面同样的见解解释了为什么允许这样做:copy构造函数得到一个 SubTest& 而不仅仅是从 基部 ,此构造函数显然位于 子测验 抽象。这个 子测验 假定编码器熟悉预期的设计/封装 子测验 提供,并且副本构造函数被授予在另一个上绕过和强制post条件/不变量的访问权限 亚测试和 也反对。(您正在从一个对象复制,该对象本身可能是由同一个函数构造的复制,因此在 *this “side而不是ref side的参数根本没有太多保护,甚至忽略了您可能想要/需要访问的所有合理原因)。

    有可能 子测验 -派生对象将意外传递给 子测验 复制构造函数(“切片”),但即使在这种情况下 亚测试和 类可以控制进一步派生对象是否可以做任何意想不到的事情。 _protMember -添加一个 private using BaseTest::_protMember; 声明如果它想“最终”获得 保护物 禁止任何派生类使用它。

        2
  •  6
  •   Community Egal    7 年前

    您可以访问 protected 仅类实例中的成员。即:

    class SubTest : public BaseTest
    {
        SubTest(const BaseTest &baseTest)
        {
            _protMember = baseTest._protMember;
         // ^^^^^^^^^^^ Is good because you are in the instance of its class
            _protMember = baseTest._protMember;
         //               ^^^^^^^^^^^^^^^^^^^^^ Produce error because you are not in the baseTest instance.              
        };
    
        // followup question
        SubTest(const SubTest &subTest)
        {
            _protMember = subTest._protMember;
          // Compile because access modifiers work on class level, and not on object level.
        };
    };
    

    后续编辑:

    访问修饰符工作在类级别,而不是对象级别。

    也就是说,同一个类的两个对象可以访问彼此的私有成员。

    这是我的消息来源: Why can I access private variables in the copy constructor?

        3
  •  0
  •   Kolyunya    11 年前

    通过定义 _protMember 作为 protected 允许派生类的对象访问 他们自己 保护物 . 这并不意味着派生类的所有对象都可以访问。 保护物 其他物体。