访问派生类中的基类成员

新手上路,请多包涵

我有一个简单的类如下

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();
}

How can I set the value of the protected instance variable A::x from an instance of the derived class B without creating an instance of class A .

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

原文由 Vijay 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 409
2 个回答

B A ,因此创建 B 的实例是创建 —c1bc848ad7d96138 的实例 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';
}

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

原文由 ildjarn 发布,翻译遵循 CC BY-SA 2.5 许可协议

请注意,B 没有对 A::x 的完全访问权限。它只能通过 B 的实例访问该成员,而不是 A 类型的任何内容或从 A 派生的任何内容。

您可以使用一种解决方法:

 class A
{
  protected:
   int x;
   static int& getX( A& a )
   {
      return a.x;
   }

   static int getX( A const& a )
   {
     return a.x;
   }
};

现在使用 getX,从 A 派生的类(如 B)可以访问任何 A 类的 x 成员。

你也知道友谊不是传递的或继承的。通过提供访问功能,可以针对这些情况进行相同的“解决方法”。

在您的情况下,您实际上可以通过您的 B 通过拥有访问它的公共功能来提供对 x 的“公共”访问。当然,在实际编程中,它受到保护是有原因的,你不想让所有东西都完全访问,但你可以。

原文由 CashCow 发布,翻译遵循 CC BY-SA 2.5 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题