内联函数应该在头文件中定义,这一点不同于其他函数。
编译器隐式地将在类内定义的成员函数当作内联函数
每个成员函数(static 成员函数外)都有一个额外的、隐含的形参 this。在调用成员函数时,形参 this 初始化为调用函数的对象的地址。
IO 类型在三个独立的头文件中定义:iostream 定义读写控制窗口的类型,fstream 定义读写已命名文件的类型,而 sstream 所定义的类型则用于读写存储在内存中的 string 对象。在 fstream 和 sstream 里定义的每种类型都是从 iostream 头文件中定义的相关类型派生而来。
如果函数有基类类型的引用形参时,可以给函数传递其派生类型的对象
每个 IO 对象管理一个缓冲区,用于存储程序读写的数据。
假设 ifile 和 ofile 是存储希望读写的文件名的 strings 对象,可如下编写代码:
// construct an ifstream and bind it to the file named ifile
ifstream infile(ifile.c_str());
// ofstream output file object to write file named ofile
ofstream outfile(ofile.c_str());
/ for each file in the vector
while (it != files.end()) {
ifstream input(it->c_str()); // open the file;
// if the file is ok, read and "process" the input
if (!input)
break; // error: bail out!
while(input >> s) // do the work on this file
process(s);
++it; // increment iterator to get
next file
}
对于用 ofstream 打开的文件,要保存文件中存在的数据,唯一方法是显式地指定 app 模式打开:
// output mode by default; truncates file named "file1"
ofstream outfile("file1");
// equivalent effect: "file1" is explicitly truncated
ofstream outfile2("file1", ofstream::out | ofstream::trunc);
// append mode; adds new data at end of existing file named "file2"
ofstream appfile("file2", ofstream::app);
// opens in binding it to the given file
ifstream& open_file(ifstream &in, const string &file)
{
in.close(); // close in case it was already open
in.clear(); // clear any existing errors
// if the open fails, the stream will be in an invalid state
in.open(file.c_str()); // open the file we were given
return in; // condition state is good if open succeeded
}
iostream 标准库支持内存中的输入/输出,只要将流与存储在程序内存中的 string 对象捆绑起来即可
string line, word; // will hold a line and word from input,
respectively
while (getline(cin, line)) { // read a line from the
input into line
// do per-line processing
istringstream stream(line); // bind to streamto the
line we read
while (stream >> word){ // read a word from line
// do per-word processing
}
}
sstream 输入和输出操作可自动地把算术类型转化为相应的 string 表示形式,反过来也可以。
int val1 = 512, val2 = 1024;
ostringstream format_message;
// ok: converts values to a string representation
format_message << "val1: " << val1 << "\n"
<< "val2: " << val2 << "\n";
// str member obtains the string associated with a stringstream
istringstream input_istring(format_message.str());
string dump; // place to dump the labels from the formatted message
// extracts the stored ascii values, converting back to arithmetic
types
input_istring >> dump >> val1 >> dump >> val2;
cout << val1 << " " << val2 << endl; // prints 512 1024