In this section we will write a C++(www.cppentry.com) version of the CSV library to address some of the remaining limitations of the C version. This will entail some changes to the specification, of which the most important is that the functions will handle C++(www.cppentry.com) strings instead of C character arrays. The use of C++(www.cppentry.com) strings will automati- cally resolve some of the storage management issues, since the library functions will manage the memory for us. In particular, the field routines will return strings that can be modified by the caller, a more flexible design than the previous version.
A class Csv defines the public face, while neatly hiding the variables and functions of the implementation. Since a class object contains all the state for an instance, we can instantiate multiple Csv variables; each is independent of the others so multiple CSV input streams can operate at the same time.
如果大家熟悉Java中的ResultSet类,或者Visual C++(www.cppentry.com)中的CRecordSet类,就会发现这个Csv类与SQL查询结果的ResultSet类很像,它维护着一个读取指针,当调用 getline( )函数之后,指针会指向下一行,这时候才能使用getfield( )来读取指定列的 值。这样的设计对程序员用户来说有一定的要求,如果一个不明就里的程序员什么 都没做,就直接调用了getfield( ),可能就会得到意想不到的结果。
感兴趣的读者可以尝试重构这个Csv类,使之更安全。譬如,将getline( )改名为 getNextLine( ),并让它返回一个CsvLine对象,getfield( )操作则由CsvLine类来提供。 当然,关于这些设计的讨论并不是本书的重点。
Default parameters for the constructor are defined so a default Csv object will read from the standard input stream and use the normal field separator; either can be replaced with explicit values.