在构造函数中输入对象时C++类成员作用域
C++ class member scope when instatiated object in constructor
我在类构造函数中有以下代码:
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 初始值设定项列表中初始化数据成员。
相关文章:
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 对RValue对象调用的LValue ref限定成员函数
- 为什么使用 "this" 指针调用派生成员函数?
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 助记符和指向成员语法的指针
- 用于访问容器<T>数据成员的正确 API
- 内置函数可查看CPP中的成员变量
- 是否可以初始化不可复制类型的成员变量(或基类)
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 嵌套在类中时无法设置成员数据
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 将函数类成员映射到类本身内部
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 将Ref对象作为类成员
- 将包含C样式数组的对象初始化为成员变量(C++)
- 静态数据成员的问题-修复链接错误会导致编译器错误
- 将公共但非静态的成员函数与ALGLIB集成
- 多成员Constexpr结构初始化
- 我们可以访问一个不存在的联盟的成员吗