在C 中运行时从指针访问对象实例

Accessing Object Instance from Pointer during Runtime in C++

本文关键字:访问 对象 实例 指针 运行时      更新时间:2023-10-16

我正在实现XBEEP库。我发现此片段将在主要循环中工作:

libxbee::XBee xbee("xbee3", "/dev/ttyUSB0", 9600);
myCB con(xbee, "Data", &address);
con << "Hello World";

但是,由于我将在运行时创建连接,因此我修改了上述代码,以便在调用创建连接的方法时创建对象。我将它们宣布为指针,而不是作为对象:

libxbee::XBee* xbee;
connectionCB* con;

然后在打开连接时,我实例化:


void XbeeController::XbeeController::openXbeeConnection(QString port, int bRate, QString deviceAddr)
{
    baudRate = bRate;
xbee = new libxbee::XBee(DEVICE_REV, "/dev/ttyUSB0", 9600); //Burnt values for proof of concept.
con = new connectionCB(*xbee, "Data", &address);
}

我的代码现在失败

void XbeeController::XbeeController::sendXbeeMessage(std::string message)
{
con << message;
}

错误:类型的" Xbee :: ConnectionCB*’的操作数无效"answers" char*"answers" char*" to binary'operator&lt;&lt;’’ con&lt;&lt;"你好世界"; ~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~

如何将con视为对象而不是指针,以便像以前一样工作?

现在con是一个指针,但是operator<<()要求参考,并可能定义了类似的内容: connectionCB &operator<<(connectionCB &cb, const char *str);

使用: *con << "Hello World";