C++?protobuf中對不同消息內(nèi)容進行賦值的方式總結(jié)(set_、set_allocated_、mutable_、add_)
本文中用到的消息結(jié)構(gòu):
message PointLLHA {// 通用的坐標(biāo)點(經(jīng)度緯度朝向高度),所有跟坐標(biāo)相關(guān)的能夠用就統(tǒng)一用這個 optional double longitude = 1;// 經(jīng)度坐標(biāo) optional double latitude = 2;// 緯度坐標(biāo) optional double heading = 3;// 朝向 optional double altitude = 4;// 高度 optional double timestamp_sec = 5;// 時間戳 } message VehicleHeartbeat {// 無人車的心跳 optional bool is_normal = 1; optional PointLLHA vehicle_pose = 2; optional double vehicle_speed = 3; } message VehicleRoutingInfo { // 無人車全局路徑規(guī)劃的結(jié)果 repeated PointLLHA way_points = 1; }
1.簡單(非嵌套)消息內(nèi)容的賦值
簡單的消息內(nèi)容直接用set_來賦值就行。
賦值方式:
vehicle_heartbeat.set_vehicle_speed(1.2);
2.嵌套消息內(nèi)容的賦值
自己定義的復(fù)雜嵌套消息不能夠通過簡單的set_來賦值,可采取set_allocated和mutable_兩種方式,但是二者的賦值方式是不同的。
使用set_allocated_,賦值的對象需要new出來,不能用局部的,因為這里用的的是對象的指針。當(dāng)局部的對象被銷毀后,就會報錯。
錯誤的賦值方式:
PointLLHA point; point.set_longitude(116.20); point.set_latitude(39.56); vehicle_heartbeat.set_allocated_vehicle_pose(&point);// 這里傳入的是一個馬上會被銷毀的指針
使用mutable_,賦值時候,可以使用局部變量,因為在調(diào)用的時,內(nèi)部做了new操作。
賦值方式1(使用set_allocated_):
PointLLHA *point = new PointLLHA; point->set_longitude(116.20); point->set_latitude(39.56); vehicle_heartbeat.set_allocated_vehicle_pose(point);// 這里傳入的是一個指針
賦值方式2(使用mutable_):
PointLLHA point; point.set_longitude(116.20); point.set_latitude(39.56); vehicle_heartbeat.mutable_vehicle_pose()->CopyFrom(point);// 這里傳入的是一個變量,mutable內(nèi)部有一個new函數(shù)
3.重復(fù)消息內(nèi)容的賦值
帶有repeated字段的消息,通過add_依次賦值。
賦值方式:
// 第一個點 PointLLHA *way_point = vehicle_routing_info.add_way_points(); way_point->set_longitude(116.20); way_point->set_latitude(39.56); // 第二個點 PointLLHA *way_point = vehicle_routing_info.add_way_points(); way_point->set_longitude(116.21); way_point->set_latitude(39.57);
總結(jié)
到此這篇關(guān)于C++ protobuf中對不同消息內(nèi)容進行賦值的文章就介紹到這了,更多相關(guān)C++ protobuf對不同消息內(nèi)容賦值內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Qt物聯(lián)網(wǎng)管理平臺之實現(xiàn)告警短信轉(zhuǎn)發(fā)
系統(tǒng)在運行過程中,會實時采集設(shè)備的數(shù)據(jù),當(dāng)采集到的數(shù)據(jù)發(fā)生報警后,可以將報警信息以短信的形式發(fā)送給指定的管理員。本文將利用Qt實現(xiàn)告警短信轉(zhuǎn)發(fā),感興趣的可以嘗試一下2022-07-07舉例解析設(shè)計模式中的工廠方法模式在C++編程中的運用
這篇文章主要介紹了設(shè)計模式中的工廠方法模式在C++編程中的運用,文中也對簡單工廠模式和工廠方法模式進行了簡單的對比,需要的朋友可以參考下2016-03-03