Game Coding Complete 4th ed. by Mike McShaffry and David Graham
(67-68) 说类应该使用流来初始化对象:
class AnimationPath
{
public:
AnimationPath();
Initialize(std::vector<AnimationPathPoint> const & srcPath);
Initialize(InputStream & stream);
//of course lots more code follows.
};
This class has a default constructor and two ways to initialize it. The first is through a classic parameter list, in this case, a list of
AnimationPathPoint
s. The second initializes the class through a stream object. This is cool because you can initialize objects from a disk, a memory stream or even the network....(Mr. Graham, the author of the chapter containing the quote, goes on the explain why using a stream as an argument to a constructor is bad. Streams could fail and your object is in a failed state.
我的问题是,不是使用此策略,而是为什么不使用流运算符 operator<<
和operator>>
代替或补充 Initialize
方法。 (Initialize
方法甚至可以只是流运算符的委托(delegate)。)
差异是语义上的还是有合理的理由使用其中之一?
最佳答案
operator<<
和operator>>
是令人厌恶的,也是 C++ IOStreams 库的最大错误之一。切勿复制该模式。采取明确的 std::istream&
(或您的框架的等效框架)更有意义。
一种更简洁的方法(尽管并不总是最可行)是拥有一个完全独立的 AnimationPathSerializer
处理将流映射到 AnimationPath
对象。保持每种类型/对象很小并且只关注一个问题。动画不需要知道如何加载或保存自身以成为动画,并且有时您可能希望支持几种完全不同的具有非常不同语义的序列化格式(因此单个通用流类型或单个序列化对象中的接口(interface)没有意义)。
关于c++ - 对象初始化: Init method or stream operator?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24225128/