使用Snmp++库时OctetStr无法接收std::string参数的报错求助
问题
使用Snmp++库的OctetStr类型时,直接传入std::string变量会触发编译错误:
error: no matching function call to Snmp_pp::OctetStr::OctetStr(std::string&)
直接用字符串字面量初始化是正常的:
Snmp_pp::OctetStr m_userName = Snmp_pp::OctetStr("username");
但尝试从结构体的std::string成员初始化OctetStr变量时就会报错,相关代码如下:
结构体定义
struct EthernetData{ std::string userName; EthernetData() : userName("") {} }
SnmpC类构造函数代码
SnmpC::SnmpC(EthernetData ethernetData) { m_userName = Snmp_pp::OctetStr(ethernetData.userName); }
类成员声明(main.hpp)
private: Snmp_pp::OctetStr m_userName;
解决方法
Snmp++的OctetStr类没有提供直接接收std::string的构造函数,但它支持const char*类型的参数。你只需要调用std::string的c_str()方法获取C风格字符串指针,再传入OctetStr构造函数即可:
修改后的构造函数代码:
SnmpC::SnmpC(EthernetData ethernetData) { m_userName = Snmp_pp::OctetStr(ethernetData.userName.c_str()); }
另外注意代码中的笔误:你写的Snmp_pp::OctetString是错误的,应该和成员变量类型保持一致,使用Snmp_pp::OctetStr。
内容的提问来源于stack exchange,提问作者xScub
相关产品推荐
相关产品推荐

