假设我在.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() { ... } };
解决方法
Protocol Buffers and O-O Design@H_404_20@ Protocol buffer classes are basically@H_404_20@ dumb data holders (like structs in@H_404_20@ C++); they don’t make good first class@H_404_20@ citizens in an object model. If you@H_404_20@ want to add richer behavIoUr to a@H_404_20@ generated class,the best way to do@H_404_20@ this is to wrap the generated protocol@H_404_20@ buffer class in an@H_404_20@ application-specific class. … You@H_404_20@ should never add behavIoUr to the@H_404_20@ generated classes by inheriting from@H_404_20@ them. This will break internal@H_404_20@ mechanisms and is not good@H_404_20@ object-oriented practice anyway.
如果你只想要一种方法,我可以看到这样的建议看起来很烦人,但总的来说这是一个非常好的建议.如果您真的没有其他功能可以保证创建特定于应用程序的“Person”类,那么定义顶级函数没有任何问题:
string concatenateNameEmail(const proto::Person &person) { ... }