一, optional 修饰符的使用
message CystalWeek
{
repeated int32 difficulty = 1;
}
//晶体的玩家的数据
message CrystalWeekData
{
optional CystalWeek data = 1; // 难度 ESWCDT_Max 4中//message CrystalWeekData
}
使用
//============================================================================
// Name : protoc.cpp
// Author : songli
// Version :
// Copyright : Your copyright notice KCP
// Description : Hello World in C, Ansi-style
//============================================================================
#include <stdio.h>
#include <stdlib.h>
#include "CrystalWeek.pb.h"
#include <iostream>
int main(void) {
CrystalWeekData cwd;
CystalWeek cw;
cw.mutable_difficulty()->Resize( 1, 0);
cw.set_difficulty(0, 2);
cwd.set_allocated_data(&cw);
for (int i = 0;i < cwd.data().difficulty_size(); ++i)
{
std::cout << cwd.data().difficulty(i) << std::endl;
}
cwd.release_data();
cw.mutable_difficulty()->Resize( 2, 0);
cw.set_difficulty(1, 33);
cwd.set_allocated_data(&cw);
for (int i = 0;i < cwd.data().difficulty_size(); ++i)
{
std::cout << cwd.data().difficulty(i) << std::endl;
}
//释放内存空间
cwd.release_data();
cw.mutable_difficulty()->Resize( 3, 0);
cw.set_difficulty(2, 54);
cwd.set_allocated_data(&cw);
for (int i = 0;i < cwd.data().difficulty_size(); ++i)
{
std::cout << cwd.data().difficulty(i) << std::endl;
}
//释放内存空间
cwd.release_data();
puts("!!!Hello World!!!");
return EXIT_SUCCESS;
}
效果图
g++编译命令:
g++ -o songli .cpp *.pb.cc *.pb.h -L/usr/local/lib -I/usr/local/include/google -lprotobuf -lpthread -std=c++11