我应该如何添加Protobuf消息的方法?
假设我在.proto文件中:
package proto; message Person { required string name = 1; required int32 id = 2; optional string email = 3; }
我想在消息中添加一个方法,比如字符串concatenateNameEmail().
我现在做的是我创建自己的C类,如下所示:
class Person : public proto::Person { public: Person( proto::Person const & person_ ) : proto::Person(person_) {} string concateNateNameEmail() { ... } };
解决方法
Google Protobufs特别不打算扩展.这是文档中的一个段落(在这个中间:
http://code.google.com/apis/protocolbuffers/docs/cpptutorial.html):
Protocol Buffers and O-O Design
Protocol buffer classes are basically
dumb data holders (like structs in
C++); they don’t make good first class
citizens in an object model. If you
want to add richer behavIoUr to a
generated class,the best way to do
this is to wrap the generated protocol
buffer class in an
application-specific class. … You
should never add behavIoUr to the
generated classes by inheriting from
them. This will break internal
mechanisms and is not good
object-oriented practice anyway.
如果你只想要一种方法,我可以看到这样的建议看起来很烦人,但总的来说这是一个非常好的建议.如果您真的没有其他功能可以保证创建特定于应用程序的“Person”类,那么定义顶级函数没有任何问题:
string concatenateNameEmail(const proto::Person &person) { ... }