protobuf之带有repeated成员实例使用(五)

1protoc转换为.h和.cc文件

protobuf之实例使用(四)-CSDN博客

2 .proto文件

syntax = "proto2"; 
package contacts;

//定义联系人message
message PeopleInfo 
{
    required string name = 1;    //姓名
    required int32 age = 2;      //年龄
    required string sex = 3;    //姓名
    repeated string subject = 4; //语文、数学、英语
}

3 c++代码块编写

#include 
#include 
#include 
#include "hello.pb.h"
using namespace std;
 
int main(int argc, char* argv[]) {

     string people_str; 
     contacts::PeopleInfo people; 
     people.set_age(20); 
     people.set_name("zhangsan"); 
     people.set_sex("nan"); 
     people.add_subject("yuwen"); 
     people.add_subject("shuxue"); 
     people.add_subject("yingyu"); 
     // 调⽤序列化⽅法,将序列化后的⼆进制序列存⼊string中
     if (!people.SerializeToString(&people_str))
         cout << "序列化联系⼈失败." << endl; 
     contacts::PeopleInfo peoplere; 
     // 调⽤反序列化⽅法,读取string中存放的⼆进制序列,并反序列化出对象
     if (!peoplere.ParseFromString(people_str))
         cout << "反序列化出联系⼈失败." << endl; 
 
    cout<< peoplere.name()<< " | " <<
    peoplere.age()<< " | " <

4.编译执行的序列化结果

你可能感兴趣的:(protobuf,linux,c++)