gpt4 book ai didi

c++ - 如何在成员初始化列表中传递类成员的指针?

转载 作者:太空宇宙 更新时间:2023-11-03 10:40:39 31 4
gpt4 key购买 nike

我有一个名为 HighWaterDetector 的类:

class HighWaterDetector
{
public:
HighWaterDetector(Device* device);
Device * devicePtr;
Output * output1Ptr;
CloudMsgParser * cloudMsgParserPtr;
Output output1;
NCD2Relay ncd2Relay;
CloudMsgParser cloudMsgParser;
};

构造函数:

HighWaterDetector::HighWaterDetector(Device* device): ncd2Relay(), output1(1, &ncd2Relay){
}

我正在尝试在 HighWaterDetector 的成员初始化列表中初始化 Output 的实例,但 Output 需要您将指针传递给 NCD2Relay 的实例,该实例也是 HighWaterDetector 类的成员。我的程序在输出构造函数内崩溃。这是这样做的错误方法吗?我做错了什么?

输出类:

class Output
{
public:
Output(ushort relayNum, NCD2Relay* ncd2RelayPtr);
ushort relayNum;
OutputStatus outputStatus;
int setOutputOn(void);
int setOutputOff(void);
void process(void);
NCD2Relay* ncd2RelayPtr;
};


//Output Constructor
Output::Output(ushort relayNum, NCD2Relay* ncd2RelayPtr) {
this->relayNum = relayNum;
this->ncd2RelayPtr = ncd2RelayPtr; //DOESNT CRASH IF I COMMENT THIS OUT
this->outputStatus.outFail = 0;
Serial.print("Initializing output ");
Serial.println(this->relayNum);
this->setOutputOff();
}

最佳答案

您是否注意到编译器警告?还是他们开到最大?您的成员的声明顺序可能是原因:

class HighWaterDetector
{
public:
HighWaterDetector(Device* device);
Device * devicePtr;
Output * output1Ptr;
CloudMsgParser * cloudMsgParserPtr;
Output output1; // <- This is constructed before
NCD2Relay ncd2Relay; // <- This...
CloudMsgParser cloudMsgParser;
};

但是你的构造函数是这样的:

HighWaterDetector::HighWaterDetector(Device* device): ncd2Relay(), output1(1, &ncd2Relay){ ... }

在上面的上下文中,在 output1 的构造函数中使用 ncd2Relay 的地址只是使用指向未初始化对象的指针,当您最终取消引用它时,它是未定义的行为在它的 build 之前。因此,您需要在类定义中强制执行排序...

仅引用 C++ 标准:(强调我的)[class.base.init/13]

In a non-delegating constructor, initialization proceeds in the following order:

  • First, and only for the constructor of the most derived class ([intro.object]), virtual base classes are initialized in the order they appear on a depth-first left-to-right traversal of the directed acyclic graph of base classes, where “left-to-right” is the order of appearance of the base classes in the derived class base-specifier-list.

  • Then, direct base classes are initialized in declaration order as they appear in the base-specifier-list (regardless of the order of the mem-initializers).

  • Then, non-static data members are initialized in the order they were declared in the class definition (again regardless of the order of the mem-initializers).

  • Finally, the compound-statement of the constructor body is executed.

关于c++ - 如何在成员初始化列表中传递类成员的指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38883526/

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