问题描述
原始帖子
编译时,以下代码会产生错误C2436:'__ctor':构造函数初始化器列表中的成员函数或嵌套类
在Child.h中
#include Parent.h
类子级:公共父级
{
公共级:
子级(List * pList)
:父级:: Parent(pList)
{
}
};
此处是父类:
Parent.h
class __declspec(dllimport)父类:public GrandParent
{
public:
父级(列表* pList = NULL);
}
在Parent.cpp
Parent :: Parent(List * pList)
:
m_a(1)
,m_b(1)
,GrandParent( pList)
{
}
不是很正确的制作方法子类调用父类构造函数?
PS
如果将Child构造函数的声明和实现拆分为.h和.cpp,也会发生同样的情况。我无法更改父类代码,因为它是预编译库的一部分。
在您提出建议后,@ Mape,@ Mat,@ Barry, @Praetorian
我意识到问题出在父类中。感谢您的建议,我在新帖子
根据您的示例进行了修改,可以很好地进行编译。
Parent :: Parent
应该只是 Parent
。
#define NULL 0
结构列表;
class GrandParent
{
public:
GrandParent(List * pList = NULL){}
};
类父级: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)
{
}
类别子级:公开父级
{
公开级:
子级(List * pList)
:父级(pList )
{
}
};
int main(void)
{
GrandParent grandparent(NULL);
Parent parent(NULL);
Child child(NULL);
返回0;
}
ORIGINAL POST
When compiled, the following code produces error C2436: '__ctor' : member function or nested class in constructor initializer list
in Child.h
#include Parent.h
class Child : public Parent
{
public:
Child (List* pList)
: Parent::Parent(pList)
{
}
};
Here the parent class:
in Parent.h
class __declspec(dllimport) Parent : public GrandParent
{
public:
Parent (List* pList = NULL);
}
in Parent.cpp
Parent::Parent (List* pList)
:
m_a(1)
,m_b(1)
,GrandParent(pList)
{
}
Isn't it right the way to make the Child class calling the Parent class constructor?
PSSame happens if I split declaration and implementation of Child constructor into .h and .cpp. I cannot change the parent class code, as it is part of a pre-compiled library.
AFTER YOUR SUGGESTIONS, @Mape, @Mat, @Barry, @Praetorian
I realised the problem is due to the presence of another constructor in the Parent class. Thanks to your suggestions I generated the code reproducing the error (minimal, complete and verifiable) in a new post Managing in Child class multiple constructors (with initializer-lists) of parent class
Adapted from your example, this compiles fine.Parent::Parent
should be just 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;
}
这篇关于在C ++中使用父类构造函数的Initialiser-list的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!