Accessing a base class member in derived class

前端 未结 4 1484
[愿得一人]
[愿得一人] 2020-12-28 17:20

I have a simple class as below

class A {
        protected:
        int x;
        };

class B:public A
        {
        public:
        int y;
      void s         


        
4条回答
  •  梦谈多话
    2020-12-28 17:49

    B is an A, so creating an instance of B is creating an instance of A. That being said, I'm not sure what your actual question is, so here's some code that will hopefully clarify things:

    class A
    {
    protected:
        int x;
    };
    
    class B : public A
    {
    public:
        int y;
    
        int gety() const { return y; }
        void sety(int d) { y = d; }
    
        int getx() const { return x; }
        void setx(int d) { x = d; }
    };
    
    int main()
    {
        B obj;
    
        // compiles cleanly because B::sety/gety are public
        obj.sety(10);
        std::cout << obj.gety() << '\n';
    
        // compiles cleanly because B::setx/getx are public, even though
        // they touch A::x which is protected
        obj.setx(42);
        std::cout << obj.getx() << '\n';
    
        // compiles cleanly because B::y is public
        obj.y = 20;
        std::cout << obj.y << '\n';
    
        // compilation errors because A::x is protected
        obj.x = 84;
        std::cout << obj.x << '\n';
    }
    

    obj can access A::x just as an instance of A could, because obj is implicitly an instance of A.

提交回复
热议问题