默认构造函数定义中的继承



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

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

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

很抱歉,你完全搞错了。无论你不做什么,都不是继承。

策略设计模式是关于构图的。您正在使用composition来创建策略设计模式,这是在您的代码中通过保持类似";战略;它指向一个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:完整参考书籍继承章节。

您可以编写以下内容之一:类声明中的Context(Strategy* strategy) : strategy_(strategy) {}Context(Strategy* strategy);

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

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

最新更新