【问题标题】:why it's OK to access protected variable in base class from derived instance为什么可以从派生实例访问基类中的受保护变量
【发布时间】:2016-04-11 05:40:08
【问题描述】:

下面的sn-p让我感到不解。 为什么 der._x++ 正确? 因为它是从 Derived 参数复制的临时局部变量。 它应该只对公共成员具有可访问性。 注释的语句 bs._x++ 不能通过,这应该是正确的。 请让我知道我在哪里误解!提前谢谢!

感谢您的友好回答。但我怀疑 der 是从参数复制的 Derived 对象,换句话说,它应该被视为使用初始化的 Derived 对象的客户端。它不是 *this 实例,而是另一个由复制构造函数产生的临时实例。

class Base
{
public:
    Base(int x, int y) :_x(x), _y(y){}
protected:
    int _x, _y;
};

class Derived :public Base
{
public:
    Derived(int x, int y,int z) :Base(x,y), _z(z){}
    void mem1(Base bs, Derived der) //copy constructor called. Derived::Derived(const Derived &)
    {
        der._x++;
        //bs._x++;
        _x++;
    }
private:
    int _z;
};

    int main()
    {
        Derived der(6,4,3), der1(5,3,2);
        Base bs(-5,-4);
        der1.mem1(bs, der);
        return 0;
    }

【问题讨论】:

  • 因为这就是语言的工作方式。访问权限不仅限于一个人的 this 实例。
  • protected 就是为了这个。 protected 成员可以被派生类访问,private 不能。
  • 如果希望派生类不能访问父类的成员变量,请将其标记为private。

标签: c++ inheritance copy accessibility


【解决方案1】:

der._x++可访问的,因为_der同一个Derived 类的对象,并且您正在从Derived 内部访问_x班级。

当您在一个类中时,您可以访问它的成员(有或没有对象引用)。否则(*this)._x 也将被禁止,这不是:)

但是你不能对任何其他类做同样的事情,bs._x++ 就是这种情况,因此是不允许的。

Friends 严重依赖语言的这一特性来实现。也不要忘记Singleton 没有它就无法实现(因为你在类内部调用它的private constructor)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-05
    • 2018-10-21
    • 2014-08-27
    • 2016-03-11
    • 2011-03-10
    • 2016-04-07
    • 1970-01-01
    • 2011-06-08
    相关资源
    最近更新 更多