本文内容来自于对狄泰学院 唐佐林老师 C++深度解析 课程的学习总结
前面的课程中我们学习了操作符的重载,那么 << 和 >> 操作符可以重载吗?我们来写一个类,重载 << 操作符来实现将整数和字符输出到控制台的功能。
实验代码
#include <stdio.h>
char endl = '\n';
class Console
{
private:
/* data */
public:
Console& operator << (int i)
{
printf("%d", i);
return *this;
}
Console& operator << (char c)
{
printf("%c", c);
return *this;
}
};
Console cout;
int main()
{
cout << 1 << endl;
return 0;
}
运行结果
实验结果:程序实现了整数 1 和 转义字符 ‘\n’ 输出到控制台的功能
实际上,在 C++ 标准库中已经实现了上面 Console 类的功能。
C++ 标准库
C++ 标准库并 不是 C++ 语言的一部分
C++ 标准库是由 类库 和 函数库 组成的集合
C++ 标准库中定义的类和对象都位于 std 命名空间中
C++ 标准库的头文件都 不带 .h 后缀
C++ 标准库 涵盖了C库的功能
C++ 编译环境 的组成
C++ 标准库中定义了多数的数据结构
C语言兼容库
为了兼容C语言,C++ 编译器中包含了C语言兼容库,C中的stdio.h,在C语言兼容库中为cstdio
我们来写一个程序来测试C语言兼容库对C代码的兼容
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
using namespace std;
int main()
{
printf("hello world!\n");
char *p = (char *)malloc(16);
strcpy(p, "D.T.Software");
double a = 3;
double b = 4;
double c = sqrt(a*a + b*b);
printf("c = %f\n", c);
printf("p = %s\n", p);
free(p);
return 0;
}
运行结果
实验结果,C++ 编译器的C兼容库可以对 C 语言进行很好的兼容
C++ 标准库
下面, 我们来用C++标准库 iostream 中的输入输出功能
实验代码
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
cout << "hello world!" << endl;
double a = 0;
double b = 0;
cout << "input a:";
cin >> a;
cout << "input b:";
cin >> b;
double c = sqrt(a*a + b*b);
cout << "c" << c << endl;
return 0;
}
小结
C++ 标准库是由 类库 和 函数库 组成的集合
C++ 标准库包含经典 算法 和 数据结构 的实现
C++ 标准库 涵盖了 C 库的功能
C++ 标准库位于 std 命名空间中