gpt4 book ai didi

c++ - Protocol Buffer cpp 嵌入消息

转载 作者:可可西里 更新时间:2023-11-01 15:40:06 25 4
gpt4 key购买 nike

我的 .proto 文件看起来像

message Cmd
{
int code = 1;
}

message CmdOne
{
required Cmd cmd = 1;
required int data = 2;
}

message CmdTwo
{
required Cmd cmd = 1;
required string data = 2;
}

在我的 cpp 文件中,我想声明 CmdOneCmdTwo 的对象并设置 cmddata 成员。但是生成的pb.h文件没有CmdOneCmdTwo对象的cmd成员的set方法,而是有一个 data 成员的 set 方法。如何为每个对象设置 cmd 的值?

我不想在 CmdOneCmdTwo 消息中定义消息 Cmd。我想重用 Cmd 消息,因为我有 10 条消息 CmdOneCmdTen

最佳答案

您有几个不同的选择。您可以获得指向 cmd 字段的非常量指针,然后适本地分配值:

CmdOne cmd_one;
Cmd* cmd(cmd_one.mutable_cmd());
cmd->set_code(2);
// Previous 2 lines could be simplified to:
// cmd_one.mutable_cmd()->set_code(2);

或者,如果你想将 Cmd 的构造实例传递给 CmdOne,你可以这样做:

Cmd* cmd(new Cmd);
cmd->set_code(1);

CmdOne cmd_one;
cmd_one.set_allocated_cmd(cmd); // Takes ownership of cmd -
// you don't call 'delete cmd'

来自 the docs 的“单一嵌入式消息字段”部分:

Given the message type:

message Bar {}

For either of these field definitions:

optional Bar foo = 1;
required Bar foo = 1;

The compiler will generate the following accessor methods:

...

Bar* mutable_foo()

Returns a mutable pointer to the Bar object that stores the field's value. If the field was not set prior to the call, then the returned Bar will have none of its fields set (i.e. it will be identical to a newly-allocated Bar). After calling this, has_foo() will return true and foo() will return a reference to the same instance of Bar. The pointer is invalidated by a call to Clear() or clear_foo().

...

void set_allocated_foo(Bar* bar)

Sets the Bar object to the field and frees the previous field value if it exists. If the Bar pointer is not NULL, the message takes ownership of the allocated Bar object and has_foo() will return true. Otherwise, if the Bar is NULL, the behavior is the same as calling clear_foo().

关于c++ - Protocol Buffer cpp 嵌入消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20395126/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com