简体   繁体   English

从protobuf继承C ++类

[英]Inherit C++ class from protobuf

I have objects of two types: TActionInfo and TActionStats. 我有两种类型的对象:TActionInfo和TActionStats。 The first one describes action's characteristics and the second one can "eat" the first one and maintain some statistics based on many actions. 第一个描述动作的特征,第二个可以“吃掉”第一个动作,并基于许多动作维护一些统计信息。

It is very convenient to use a protobuf in my task, because these objects are frequently serialized and deserialized. 在我的任务中使用protobuf非常方便,因为这些对象经常被序列化和反序列化。

It seems to be a good idea that TActionStats should have a method like TActionStats应该具有类似以下的方法似乎是一个好主意

bool AddAction(const TActionInfo& action);

Is it a good idea to inherit a class from from google-protobuf TActionStats class? 从google-protobuf TActionStats类继承一个类是个好主意吗? It is a good idea to inherit smth from protobuf in general? 通常,从protobuf继承smth是个好主意吗?

No, you should not subclass protobuf types. 不,您不应该继承protobuf类型。

Consider what would happen if you embedded a TActionStats inside some other message type: 考虑一下,如果将TActionStats嵌入其他某种消息类型中会发生什么:

message TEnvelope {
  optional TActionStats stats = 0;
  optional string recipient = 1;
}

Now when you call stats() or mutable_stats() on a TEnvelope , you will receive a TActionStats , not your subclass. 现在,当您在TEnvelope上调用stats()mutable_stats()时,您将收到TActionStats ,而不是您的子类。 If you have a bunch of code that expects specifically to receive your subclass, you won't be able to call that code (without making a copy), so now you have to rewrite everything. 如果您有一堆希望专门接收子类的代码,则将无法调用该代码(不进行复制),因此现在您必须重写所有内容。

Instead, write your helper methods as independent, free-standing functions. 而是将帮助程序方法编写为独立的独立函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM