建议23:尽量使用C++(www.cppentry.com)标准的iostream(2)
接下来再说说printf() 和operator<<的问题。首先通过上面的讲解我们可以知道printf()函数继承自C标准库,而operator<<是标准C++(www.cppentry.com)所独享的。对于printf()函数,大家肯定很熟悉,它是可移植的、高效的,而且是灵活的;但是正如建议15中所说的那样,因为printf()、scanf()函数不具备类型安全检查,也不能扩充,所以并不完美;而C语言遗留的问题在C++(www.cppentry.com)的operator<<中得到了很好的解决,换句话说,printf()的缺点正是operator<<的长处。现在再去回顾建议15中提到的关于Student类型对象打印的问题,用operator<<就可以完美解决了:
- class Student
- {
- public:
- Student(string& name, int age, int scoer);
- ~ Student();
- private:
- string m_name;
- int m_age;
- int m_scoer;
- friend ostream& operator<<( ostream& s, const Student& p );
- };
-
- ostream& operator<<( ostream& s, const Student& p )
- {
- s<<p. m_name<<" "<<p.m_age<<" "<<p. m_scoer;
- return s;
- }
- // 调用operator<<
- Student XiaoLi("LiLei", 23, 97);
- cout<< XiaoLi;
当然了,相比C++(www.cppentry.com) iostream程序库中的类,C中的stream函数也并不是一无是处的:
(1)一般认为C stream函数生成的可执行文件更小,有着更高的效率;Scott Meyers在《More Effective C++(www.cppentry.com)》的条款23中的测试也很好地证明了这一点;
(2)C++(www.cppentry.com) iostream程序库中的类会涉及对象构造、析构的问题,而C stream函数没有这些,所以不会像前者那样因为构造函数带来不必要的麻烦。
(3)C stream函数有着更强的可移植能力。
对于一般应用程序而言,这三条优点还不足以打动他们,抛弃C++(www.cppentry.com) iostream程序库,转而投向C stream函数。
请记住:
C++(www.cppentry.com) iostream程序库中的类与C stream函数虽然各有优点,但是一般推荐使用前者,因为类型安全与可扩充性对于我们更有吸引力,所以,建议使用#include< iostream >,而不是#include< stdio.h >、#include< cstdio >、#include< iostream.h >。