提问者:小点点

C++类成员作用域在构造函数中初始化对象时


我在类构造函数中有这样的代码:

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)

共1个答案

匿名用户

当构造函数的主体

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

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

所以在这个陈述中的身体里面

this->mqttClient = PubSubClient(wifiClient);

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

如果可能的话,可以在构造数据成员期间在构造函数的mem-initializer列表中初始化数据成员。

相关问题


MySQL Query : SELECT * FROM v9_ask_question WHERE 1=1 AND question regexp '(c++|类|成员|作用|域|构造|函数|中|初始化|对象)' ORDER BY qid DESC LIMIT 20
MySQL Error : Got error 'repetition-operator operand invalid' from regexp
MySQL Errno : 1139
Message : Got error 'repetition-operator operand invalid' from regexp
Need Help?