0

我有一个与继承有关的问题。

我声明一个类,然后声明一个子类,如下所示

`Producer::Producer(Pool<string>* p, string id) {
    mPool = p;  // protected members
    mId = id;
}

ProduceCond::ProduceCond(Pool<string>* p, string id) {
    Producer(p, id);
}

class Producer{
}

class ProduceCond : public Producer, public ThreadSubject {
}

`

虽然我在子构造函数中调用了正确的父构造函数,但我收到一个错误

ProduceCond.cpp:10:52: error: no matching function for call to ‘Producer::Producer()’

有人能告诉我为什么我会收到这个错误,尽管我使用了正确的父构造函数格式吗?

4

2 回答 2

2

您需要使用构造函数初始化列表:

ProduceCond::ProduceCond(Pool<string>* p, string id)  : Producer(p, id)
{
  ....
}

否则,您将默认构造 a Producer(您不能这样做,因为它没有默认构造函数),然后在构造函数的主体中做一些奇怪的事情。

于 2013-07-14T10:49:16.327 回答
1

初始化没有默认构造函数的子对象(基础),您需要通过成员初始化列表调用它:

ProduceCond::ProduceCond(Pool<string>* p, string id) : Producer(p, id) {}

或者您可以提供一个默认构造函数,该构造函数将由子类构造函数隐式调用

Producer() : mPool(std::nullptr) { } 

您还必须在以下情况下使用成员初始化器:

1 You must (at least, in pre-C++11) use this form to initialize a nonstatic const data
member.

2 You must use this form to initialize a reference data member.
于 2013-07-14T10:53:53.053 回答