gpt4 book ai didi

c++ - C++调用基类和派生类构造函数

转载 作者:行者123 更新时间:2023-11-28 03:50:19 25 4
gpt4 key购买 nike

#define DECLARE_NEWMSG(ClassName,ClassID)                
static ClassName* FromMsg(ClassA* psg)
{
return dynamic_cast<ClassName*>(psg);
}
static ClassA* newMsg()
{
return new ClassName;
}
enum {ID = ClassID};

GET_EVENT = 0x41,

typedef ClassA* (*pNewMsg)(void); //function pointer

typedef struct
{
int Id;
CString Ascii;
pNewMsg MessageFunc; //calls new for the particular message
} stStruct;

ClassA
{
//stmts;
};

ClassA::ClassA(int Id,pNewMsg newMsg,const char* Ascii,void* Data,size_t DataSize)
{
initialises all the variables;
}

class GetEvent : public ClassA
{
public:
DECLARE_NEWMSG(GetEvent,GET_EVENT);
GetEvent();
};


static const GetEvent cGetEvent;
GetEvent::GetEvent():ClassA( ID, newMsg, NULL, NULL, 0 )
{
//no stmts inside;
}

无法理解 GetEvent::GetEvent():ClassA( ID, NewMsg, NULL, NULL, 0 ).. 他们是否传递从派生类构造函数接收到的值,然后将其分配给基类构造函数。 .if so then newMsg will be left undefined as it gets defined while calls the base class constructor...如果采用相反的情况,则 ID 将保持未定义状态...

无法理解语句的执行,

static const GetEvent cGetEvent;
GetEvent::GetEvent():ClassA( ID, newMsg, NULL, NULL, 0 )
{
//no stmts inside;
}

还有函数指针,

typedef ClassA* (*pNewMsg)(void); 

#define DECLARE_NEWMSG(ClassName,ClassID)
static ClassName* FromMsg(ClassA* psg)
{
return dynamic_cast<ClassName*>(psg);
}
static ClassA* newMsg()
{
return new ClassName;
}

最佳答案

static const GetEvent cGetEvent;
GetEvent::GetEvent():ClassA( ID, newMsg, NULL, NULL, 0 )
{
//no stmts inside;
}

此语法称为 initialization list , 并可用于在构造期间初始化类成员。当您构造一个派生类对象时,它的父类也将被初始化(从层次结构的顶部开始)。在这种情况下,GetEvent构造函数指定如何构造 ClassA对象(尽管阅读了您的代码,classA 的实际类定义并未指定此构造函数)。

typedef ClassA* (*pNewMsg)(void); 

这个函数指针typedef意味着...

我们可以调用的函数指针pNewMesg它不带参数 ( void ) 并返回指向 ClassA 的指针对象。

在 C++ 常见问题解答中对函数指针 typedef 语法的更好解释:http://www.parashift.com/c++-faq-lite/pointers-to-members.html#faq-33.5

关于c++ - C++调用基类和派生类构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5764364/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com