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;
}
原文地址:https://www.cnblogs.com/helloweworld/p/4211480.html