在谷歌的协议缓冲区 http://code.google.com/p/protobuf/API for Java,他们使用这些漂亮的构建器来创建对象(请参阅here http://code.google.com/apis/protocolbuffers/docs/javatutorial.html#builders):
Person john =
Person.newBuilder()
.setId(1234)
.setName("John Doe")
.setEmail("[email protected] /cdn-cgi/l/email-protection")
.addPhone(
Person.PhoneNumber.newBuilder()
.setNumber("555-4321")
.setType(Person.PhoneType.HOME))
.build();
但相应的C++ API并不使用这样的Builders(参见here http://code.google.com/apis/protocolbuffers/docs/cpptutorial.html)
C++ 和 Java API 应该做同样的事情,所以我想知道为什么他们不在 C++ 中使用构建器。这背后是否有语言原因,即它不符合习惯用法或者在 C++ 中不受欢迎?或者可能只是编写 Protocol Buffers 的 C++ 版本的人的个人喜好?
在 C++ 中实现类似功能的正确方法是使用返回 *this 引用的 setter。
class Person {
std::string name;
public:
Person &setName(string const &s) { name = s; return *this; }
Person &addPhone(PhoneNumber const &n);
};
该类可以像这样使用,假设有类似定义的 PhoneNumber:
Person p = Person()
.setName("foo")
.addPhone(PhoneNumber()
.setNumber("123-4567"));
如果需要一个单独的构建器类,那么也可以这样做。应分配此类建设者
当然,在堆栈中。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)