Protobuf 基础语法与 C++ 接口速查
2026/6/30 7:43:34 网站建设 项目流程

Protobuf 基础语法与 C++ 接口速查

一、message 数据结构定义

.proto文件本质就是声明结构化数据:

message Person { optional uint32 age = 1; optional string name = 2; repeated uint32 scores = 3; }

编译后自动生成 C++ 类,等价形式:

classPerson{public:// 普通字段uint32age()const;voidset_age(uint32 value);conststd::string&name()const;voidset_name(conststd::string&value);// 数组字段intscores_size()const;uint32scores(intindex)const;voidadd_scores(uint32 value);};

二、package 命名空间

在 proto 文件最顶部声明:

package xxx;
  • proto 的package等价于 C++ 的namespace xxx
  • 使用时:xxx::Person,或者using namespace xxx;

三、字段修饰符 & C++ 操作接口

1. optional 普通字段(可选字段)

proto 定义:

optional uint32 age = 1;

C++ 接口:

person.set_age(18);// 写入值person.age();// 读取值person.has_age();// 判断字段是否被赋值person.clear_age();// 清空此字段

2. repeated 数组/列表字段

proto 定义:

repeated uint32 scores = 3;

C++ 接口:

person.add_scores(90);// 向数组追加元素person.scores_size();// 获取数组长度person.scores(0);// 读取下标为0的元素person.mutable_scores(0);// 获取可修改元素的指针(复杂对象常用)person.clear_scores();// 清空整个数组

3. message 嵌套子对象

proto 嵌套定义:

message Item { optional int32 id = 1; } message Bag { optional Item item = 1; }

C++ 接口:

bag.mutable_item()->set_id(1001);// 获取可写子对象bag.item().id();// 只读访问子对象bag.has_item();// 判断子对象是否存在bag.clear_item();// 清空子对象

四、核心方法记忆口诀

场景方法名
读取普通基础字段xxx()
修改普通基础字段set_xxx(value)
只读访问嵌套messagexxx()
获取可写嵌套messagemutable_xxx()
repeated数组元素个数xxx_size()
repeated数组追加元素add_xxx()
repeated数组读取下标元素xxx(i)
repeated数组修改下标元素mutable_xxx(i)

对象整体操作

obj.CopyFrom(other);// 完整复制另一个对象obj.Clear();// 清空所有字段obj.ShortDebugString();// 打印结构化文本,用于调试

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询