在C ++中使用父类构造函数initialiser-list

时间:2018-02-08 17:20:14

标签: c++ inheritance constructor initializer-list

原始帖子

编译时,以下代码产生错误C2436:' __ ctor' :构造函数初始化列表中的成员函数或嵌套类

在Child.h中

#include Parent.h
class  Child : public Parent  
{
    public:
        Child (List* pList) 
            : Parent::Parent(pList)
        {
        }
};

这里是父类:

在Parent.h中

class __declspec(dllimport) Parent : public GrandParent  
{
    public:
       Parent (List* pList = NULL);
}
在Parent.cpp中

Parent::Parent (List* pList)
: 
    m_a(1)
   ,m_b(1)
   ,GrandParent(pList)
{
}

让Child类调用Parent类构造函数的方法是否正确?

PS 如果我将Child构造函数的声明和实现拆分为.h和.cpp,也会发生同样的情况。我无法更改父类代码,因为它是预编译库的一部分。

在你的建议之后,@ Mape,@ Mat,@ Barry,@ Praetorian

我意识到问题是由于Parent类中存在另一个构造函数。感谢您的建议,我在新帖Managing in Child class multiple constructors (with initializer-lists) of parent class

中生成了重现错误(最小,完整和可验证)的代码

1 个答案:

答案 0 :(得分:0)

改编自你的例子,编译得很好。 Parent::Parent应该只是Parent

#define NULL 0

struct List;

class GrandParent
{
    public:
       GrandParent(List* pList = NULL) {}
};


class Parent : public GrandParent
{
    public:
       Parent(List* pList = NULL);
       int m_a;
       int m_b;
};

Parent::Parent(List* pList)
:
    m_a(1)
   ,m_b(1)
   ,GrandParent(pList)
{
}

class  Child : public Parent
{
    public:
        Child (List* pList)
            : Parent(pList)
        {
        }
};

int main(void)
{
    GrandParent grandparent(NULL);
    Parent parent(NULL);
    Child child(NULL);

    return 0;
}
相关问题