1、有趣的重载
操作符 << 的原生意义是按位左移,例: 1 << 2 ;
其意义就是将整数 1 按位左移 2 位,即 0000 0001——> 0000 0100
重载左移操作符,将 变量或常量 左移到 一个对象 中!
我们可以写一个重载函数看看会发生什么?
Console 的意思就是命令行
#include <stdio.h>
class Console //命令行
{
public:
void operator <<(int i)
{
printf("%d", i);
}
};
Console cout;
int main()
{
cout << 1; //将 1 这个整数左移到 命令行 对象,将 1 输出到命令行
return 0;
}
cout 是命令行的一个全局对象,把 1 左移到 cout,函数里面的意思就是把 1 输出到命令行。有了这个原理,我们可以在这个基础上做很多的重载。
#include <stdio.h>
const char endl = '\n';
class Console
{
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;
}
在这里我们重载了字符的左移,并且把换行定义为了endl,返回值改成了类名重载,这样实现了连续的输出。然后我们可以重载字符串或者double 类型
#include <stdio.h>
const char endl = '\n';
class Console
{
public:
Console& operator <<(int i)
{
printf("%d", i);
return *this;
}
Console& operator <<(char c)
{
printf("%c", c);
return *this;
}
Console& operator <<(const char* s)
{
printf("%s", s);
return *this;
}
Console& operator <<(double d)
{
printf("%lf", d);
return *this;
}
};
Console cout;
int main()
{
cout << 1 << endl;
cout << "xiebs nb!" << endl;
double d1 = 0.1;
double d2 = 0.2;
cout << d1 + d2 << endl;
return 0;
}
写完这个程序,发现有一个特别好的好处,就是你不用写数据的类型。在main 函数里面再也看不到 printf 但是也能进行输出,再也看不到格式化字符串了,因为编译器会通过重载机制为我们自动选择究竟使用哪一个重载函数,我们可以避开反复输入格式化字符串,这是一种革新。也是为后续写cpp代码做了很好的铺垫。
2、C++ 标准库
- C++ 标准库并不是C++ 语言的一部分
- C++ 标准库是由类库和函数库组成的集合
- C++ 标准库中定义的类和对象都位于std 命名空间中
- C++ 标准库的头文件都不带.h后缀
- C++ 标准库涵盖了C库的功能
C++编译环境的组成
C兼容库
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
C++标准库
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
using namespace std;
int main()
{
printf("hello,world\n");
char* p = (char*)malloc(16);
strcpy(p, "xiebs");
double a = 3;
double b = 4;
double c = sqrt(a*a + b*b);
printf("c = %lf\n", c);
free(p);
return 0;
}
C++里面有两个全局对象 cout 、cin
#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 命名空间中