【问题标题】:Superclass Setting Object of Subclass Data子类数据的超类设置对象
【发布时间】:2017-01-23 16:11:44
【问题描述】:

我在 C++ 中有一个基类,它有一些受保护的成员变量(尽管在这种情况下,我认为它是受保护的还是私有的并不相关)。

我有一个派生自这个基类的派生类。其中,有一个公共函数创建基类的对象并返回该对象。但是,在该函数中,我需要能够将受保护的成员变量设置为特殊状态。

例子:

class Base
{
protected:
  int b_value;
};

class Derived : public Base
{
public:
  Base createBase()
  {
    Base b;
    b.b_value = 10;
    return b;
  }
};

我特别希望派生类能够受保护的成员变量。我不想要基类中的公共访问器方法。

我最初试图通过使派生类的 createBase() 函数成为基类的朋友来解决这个问题。像这样:

class Base
{
protected:
  int b_value;
  friend Base Derived::createBase();
};

class Derived : public Base
{
public:
  Base createBase()
  {
    Base b;
    b.b_value = 10;
    return b;
  }
};

如您所见,由于尚未定义 Derived,因此无法编译。如果重要的话,这两个类是在单独的头文件中定义的。我想描述这个问题的一种方式是“鸡和蛋”问题,其中一个需要另一个。

我觉得这一定是“我没有正确设计我的课程,需要重新考虑我是如何做到这一点的”,但我不知道如何让它发挥作用。

【问题讨论】:

    标签: c++ class inheritance friend


    【解决方案1】:

    您可以转发声明Derived,然后在Base 中加为好友:

    class Derived;
    class Base
    {
        friend class Derived;
    protected:
      int b_value;
    };
    
    class Derived : public Base
    {
    public:
      Base createBase()
      {
        Base b;
        b.b_value = 10;
        return b;
      }
    };
    

    但是,正如您已经说过的那样,这种设计对我来说似乎存在严重缺陷,您可能应该在您的 Base 类中将 createBase() 设为静态公共方法,并为 b_value 设置一个设置器或设置它的构造函数。

    请记住,现在createBase() 内部,this->b_value 也可用。

    【讨论】:

    • 前向声明在这里有效吗?这两个类在单独的头文件中定义。你需要在 Base.hpp 中 #include "Derived.hpp" 这不会编译。
    • @TLytle 不,这就是前向声明的问题,您不要在基础 .hpp 中包含派生,而是使用前向,这样就可以了。
    猜你喜欢
    • 2015-04-07
    • 1970-01-01
    • 2018-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-28
    相关资源
    最近更新 更多