访问派生类中的基类成员

Vij*_*jay 14 c++ inheritance

我有一个简单的课程如下

class A {
        protected:
        int x;
        };

class B:public A
        {
        public:
        int y;
      void sety(int d)
        {
        y=d;
        }
        int gety(){ return y;}
        };

int main()  
{
B obj;
obj.sety(10);
cout<<obj.gety();
getch();
}
Run Code Online (Sandbox Code Playgroud)

如何在不创建实例的情况下从派生protected实例设置实例变量的值.A::xclass Bclass A

编辑:我们可以访问A::x使用B对象的值吗?喜欢obj.x

ild*_*arn 12

B 是一个 A,所以创建一个实例B是创建一个实例A.话虽这么说,我不确定你的实际问题是什么,所以这里有一些代码可以澄清事情:

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';
}
Run Code Online (Sandbox Code Playgroud)

obj可以A::x像can 的实例一样访问A,因为它obj是隐式的实例A.