protobuf--嵌套repeated get set

package test_namespace;

message ChildMsg {
    message GrandSonMsg {
        optional string grandson = 1;    
    }

    repeated GrandSonMsg grandson_msg = 1;
}

message FatherMsg {
    repeated ChildMsg child_msg = 1;
}


#include <iostream>
#include "test.pb.h"

using namespace std;

int main()
{
    // 方式2
    /*
    test_namespace::FatherMsg father_msg; 
    test_namespace::ChildMsg* ch;
    test_namespace::ChildMsg::GrandSonMsg* gs;

    ch = father_msg.add_child_msg();

    gs = ch->add_grandson_msg();
    gs->set_grandson("hello");

    gs = ch->add_grandson_msg();
    gs->set_grandson("world");

    */

    // 方式1(建议)
    test_namespace::FatherMsg father_msg; 

    test_namespace::ChildMsg child_msg;
    child_msg.add_grandson_msg()->set_grandson("hello");
    child_msg.add_grandson_msg()->set_grandson("world");

    father_msg.add_child_msg()->CopyFrom(child_msg);


    // output
    for (int i = 0; i < father_msg.child_msg_size(); i++)
    {
        for (int j = 0; j < father_msg.child_msg(i).grandson_msg_size(); j++)
        {
            cout << father_msg.child_msg(i).grandson_msg(j).grandson() << endl;
        }
    }


    return 0;
}

 

posted @ 2015-01-08 17:43  helloweworld  阅读(1398)  评论(0编辑  收藏  举报