在构造函数中输入对象时C++类成员作用域

C++ class member scope when instatiated object in constructor

本文关键字:C++ 成员 作用域 对象 构造函数 输入      更新时间:2023-10-16

我在类构造函数中有以下代码:

MqttSensorInterface::MqttSensorInterface(Client& client, String sensorTopic)
{
this->mqttClient = PubSubClient(client);
this->sensorTopic = sensorTopic;
this->askMeasureTopic = sensorTopic + "/askmeasure";
this->publishMeasureTopic = sensorTopic + "/measure";
}

但是,在创建新的MqttSensorInterface对象时使用构造函数之后,构造函数中实例化的PubSubClient对象将被销毁(PubSubClient析构函数被调用(。我是C++新手,不知道这段代码是否有问题。由于PubSubClient对象在构造函数中实例化,但类成员mqttClient设置为此对象,因此其作用域是什么?

PubSubClient 构造函数代码:

PubSubClient::PubSubClient(Client& client) {
this->_state = MQTT_DISCONNECTED;
setClient(client);
this->stream = NULL;
this->bufferSize = 0;
setBufferSize(MQTT_MAX_PACKET_SIZE);
setKeepAlive(MQTT_KEEPALIVE);
setSocketTimeout(MQTT_SOCKET_TIMEOUT);
}

编辑

通过以下方式使用成员初始值设定项列表解决:

MqttSensorInterface::MqttSensorInterface( Client& client, String sensorTopic): mqttClient(client)

当构造函数的主体

MqttSensorInterface::MqttSensorInterface(String sensorTopic)
{
WiFiClient wiFiClient;
this->mqttClient = PubSubClient(wifiClient);
this->sensorTopic = sensorTopic;
this->askMeasureTopic = sensorTopic + "/askmeasure";
this->publishMeasureTopic = sensorTopic + "/measure";
}

获取已使用默认构造函数创建的数据成员 mqttClient 的控件PubSubClient前提是在类定义中没有数据成员的显式初始值设定项,

所以在这个声明中的身体内部

this->mqttClient = PubSubClient(wifiClient);

通过显式调用构造函数PubSubClient(wifiClient)创建了PubSubClient类型的临时对象,并使用复制赋值运算符或移动赋值运算符将此临时对象分配给数据成员this->mqttClient。在语句执行结束时,临时对象将被销毁。

如果可能,可以在构造数据成员期间在构造函数的 mem 初始值设定项列表中初始化数据成员。