【问题标题】:Inheritance In Default Constructor Definition默认构造函数定义中的继承
【发布时间】:2020-07-29 17:42:41
【问题描述】:

我一直在学习设计模式,在我的策略设计模式的实现中,我发现我不能像这样在类定义中声明继承:

class Context
{
private:
    Strategy *strategy_;
public:
    Context(Strategy* strategy) : strategy_(strategy); // This line
    ~Context();
    void set_strategy(Strategy* strategy);
    void DoStuff() const;
};

通过将默认构造函数更改为在我的类定义中工作正常

Context(Strategy* strategy=nullptr) : strategy_(strategy){}

或者通过从定义中删除继承并像这样在类之外定义它。

class Context
{
private:
    Strategy *strategy_;
public:
    Context(Strategy* strategy); // This line
    ~Context();
    void set_strategy(Strategy* strategy);
    void DoStuff() const;
};

Context::Context(Strategy *strategy=nullptr) : strategy_(strategy){} // and this line

我很好奇为什么不能在类定义的默认构造函数中声明继承。

【问题讨论】:

  • 您不能在构造函数中编写继承。你写的是member initialization list
  • 我在您的代码中没有看到任何与继承有关的内容?
  • 不确定这是否是切线,但像 m_strategy 这样的东西可以让您和 IDE/编辑器更轻松地从列表中挑选成员。
  • 这是一个运算符重载的例子,有没有办法使用':'进行继承?很抱歉造成混乱。
  • @ClockworkKettle :在这两种情况下都不是运算符。这只是语法的一部分。

标签: c++ inheritance constructor


【解决方案1】:

很抱歉,您完全搞错了。无论你没有做什么,它根本就不是继承。

策略设计模式是关于组合的。您正在使用组合来创建策略设计模式,该模式在您的代码中完成,方法是保留指向 Strategy 对象的“Strategy *strategy_”之类的指针。因此,可以说您正在使用合成。

如果有一个类A继承了类B,在cpp中我们这样写:

class A {
  // private variables write here
  int x_, y_;
  // private methods
  void somePrivateMethod() {
  }
public:
  // public variable write here
  int x, y;
  // public methods
  A() {
  }
  void somePublicMethod() {
  }
}

class B : public A {
  int u, v, w;
public:
  int z;
  B() {
  }
  void someMethodInB() {
  }
}

关于 cpp 继承的更多信息,我建议你看看 Herbert Schild 的CPP: The complete reference 书籍 继承章节。

【讨论】:

  • 感谢推荐!我会试着拿到一份副本。
【解决方案2】:

你写了以下之一: Context(Strategy* strategy) : strategy_(strategy) {}Context(Strategy* strategy); 在你的类声明中。

那个冒号根本不表示继承这里,而是直接成员初始化。在 C++ 中使用它是一件非常好的事情,我强烈推荐它。但是你在实现构造函数时使用它。

继承是在类本身上完成的:
class Foo : public Bar {}; // class Foo inherits Bar publicly

【讨论】:

    猜你喜欢
    • 2016-03-24
    • 2011-05-20
    • 2017-10-04
    • 2015-07-09
    • 1970-01-01
    • 1970-01-01
    • 2010-10-06
    • 2013-05-22
    • 1970-01-01
    相关资源
    最近更新 更多