我们要用c++语言打印“HelloWorld!\n”怎么实现?
std::cout << "HelloWorld" << std::endl;当然,前提要包含c++标准库的头文件
#include <iostream>前面学习了操作符重载,”<<”原先是单片机程序中用得最多的左移操作符,在这里它成了一个可以向控制台打印数据的功能的符号,根据学习了操作符重载,显然,c++标准库对”<<”操作符进行了重载。
它是如何实现的?可以这样: 定义控制台类,其间只有一个”<<”操作符重载函数
class console { public: void operator<< (int i); }; void console::operator<< (int i) { printf("%d", i); }利用该类实例化全局对象cout,通过cout调用operator<<()函数。
console cout; int main(void) { int a = 6; cout.operator<<(a); return 0; }程序运行正常:
同理,我们可以不通过对象显示调用operator<<,直接使用符号<<
cout << a;运行结果一致。 利用函数重载规则,我们还可以定义打印字符型的<<重载函数:
void console::operator<< (char c) { printf("%c", c); } int main(void) { int a = 6; cout << a; cout << '\n'; return 0; }编译运行:
换行符’\n’要用endl代替:
const char endl = '\n'; //... cout << a; cout << endl;现在要将如上两句打印合二为一:
cout << a << endl;编译出错: 原因在于,operator<< (int i)的返回值为空,而”<< endl”又是调用operator<< (int i)的返回值的operator<< (char c)函数。修改很简单,将操作符重载函数的返回值为cout对象即可实现连续打印了:
class console { public: console& operator<< (int i); console& operator<< (char c); }; console& console::operator<< (int i) { printf("%d", i); return *this; } console& console::operator<< (char c) { printf("%c", c); return *this; }要想打印double类型,字符串类型等等,只需要再去定义对应类型的重载函数即可。 对了,我们不加作用域限定,默认是全局作用域。在使用c++标准库的时候需要指定命名空间std,我们同样可以仿照:
namespace my_std{ const char endl = '\n'; class console { public: console& operator<< (int i); console& operator<< (char c); }; console cout; } using namespace my_std; console& console::operator<< (int i) { printf("%d", i); return *this; } console& console::operator<< (char c) { printf("%c", c); return *this; } int main(void) { int a = 6; my_std::cout << a << my_std::endl; return 0; }