zoukankan      html  css  js  c++  java
  • protobuf--repeated get set

    普通字段
    package test_namespace;
    
    message FatherMsg {
        repeated string father = 1;    
    }
    #include <stdio.h>
    #include <iostream>
    #include <string>
    
    #include "test.pb.h"
    
    using namespace std;
    
    int main()
    {
        // 方式1
        /*
        test_namespace::FatherMsg father_msg;
    
        string* str1 = father_msg.add_father();
        *str1 = string("hello");
    
        string* str2 = father_msg.add_father();
        *str2 = string("world");
    
        for (int i = 0; i < father_msg.father_size(); i++)
        {
            cout << father_msg.father(i) << endl; 
        }
        */
        // 方式2 (建议)
        test_namespace::FatherMsg father_msg;
        father_msg.add_father("hello");
        father_msg.add_father("world");
    
        for (int i = 0; i < father_msg.father_size(); i++)
        {
            cout << father_msg.father(i) << endl; 
        }
        
        return 0;
    }
    message字段

    package test_namespace; message ChildMsg { optional
    string child = 1; } message FatherMsg { repeated ChildMsg child_msg = 1; }
    #include <stdio.h>
    #include <iostream>
    #include <string>
    
    #include "test.pb.h"
    
    using namespace std;
    
    int main()
    {
        // 方式1(建议)
        test_namespace::FatherMsg father_msg; 
        test_namespace::ChildMsg* ch;  // 如果ChildMsg嵌套在FatherMsg中, 则为test_namespace::FatherMsg::ChildMsg* ch;
    
        ch = father_msg.add_child_msg();
        ch->set_child("hello");
        ch = father_msg.add_child_msg();
        ch->set_child("world");
    
        /*
        // 方式2 如果需要设置child_msg多个成员, 则不适用
        test_namespace::FatherMsg father_msg; 
    
        father_msg.add_child_msg()->set_child("hello");
        father_msg.add_child_msg()->set_child("world");
    
    
        // 方式3
        test_namespace::FatherMsg father_msg; 
    
        father_msg.add_child_msg();
        father_msg.mutable_child_msg(0)->set_child("hello");
        father_msg.add_child_msg();
        father_msg.mutable_child_msg(1)->set_child("world");
       
        */ 
    
        // output
        for (int i = 0; i < father_msg.child_msg_size(); i++)
        {
            cout << father_msg.child_msg(i).child() << endl; 
        }
    
        return 0;
    }
  • 相关阅读:
    计算小于12的阶乘
    ubuntu下gvim启动出现gtk warning Invalid input string
    UBUNTU基础知识
    Ubuntu下创建软链接
    linux命令行介绍及使用(二)
    Ubuntu问题sudo: /etc/sudoers is mode 0640should be 0440的解决方法
    安装mp3插件
    Ubuntu下GTK的安装
    linux命令行介绍及使用(三)
    VB.NET中用GDI+画饼图
  • 原文地址:https://www.cnblogs.com/helloweworld/p/4211480.html
Copyright © 2011-2022 走看看