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

C++中的值访问

  •  0
  • Sijith  · 技术社区  · 14 年前

    你好,

    这里A继承了B,现在我想从A访问B中的一个变量,我在B中包含了一个头并试图访问,但在QObject中显示了一些错误。

    有可能这样做吗。。请帮忙

    2 回复  |  直到 14 年前
        1
  •  3
  •   wengseng    14 年前

    我不确定我能正确理解你的问题。。。。

    class A {
    public:
      int nValueA;
    protected:
      int nValueB;
    private:
      int nValueC;
    };
    
    class B : public A {
    public:
        B();
        int x, y, z;
    }; 
    B::B(): 
    x(nValueA), //-->OK
    y(nValueB), //-->OK
    z(nValueC)  //-->error due to child can't inherit parent's private member
    {}
    
    void main(){
      B object;
      object.nValueA = 888; //--> valid
      object.nValueB = 888; //--> error since protected member is not accessible
      object.nValueC = 888; //--> error since private member is not accessible
    }
    

    class A {
    public:
      int nValueA;
      int nValueB;
      int nValueC;
    };
    
        2
  •  1
  •   Benoit    14 年前

    是您的成员变量 private protected .