第32课 初探C++标准库
重载左移操作符
操作符 << 的原生意义是按位左移,例:
1 << 2;
其意义是将整数1按位左移2位,即:
0000 0001 -----> 0000 0100
重载左移操作符,将变量或常量左移到一个对象中。
#include <stdio.h>
class Console
{
public:
void operator << (int n)
{
printf("%d",n);
}
void operator <<(char c)
{
printf("%c",c);
}
};
Console cout;
int main()
{
// cout.operator <<(1);
cout << 1; //与上面那种形式等价
cout <<'\n';
return 0;
}
将程序进一步优化,将设在main函数中这样写:
cout << 1 << '\n',这样写编译时会出错。
#include <stdio.h>
class Console
{
public:
Console& operator << (int n)
{
printf("%d",n);
return *this;
}
Console& operator <<(char c)
{
printf("%c",c);
return *this;
}
};
Console cout;
int main()
{
// cout.operator <<(1);
cout << 1 << '\n';
return 0;
}
继续优化:
#include <stdio.h>
const char endl = '\n';
class Console
{
public:
Console& operator << (int n)
{
printf("%d",n);
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("%f",d);
return *this;
}
};
Console cout;
int main()
{
cout << 1 << '\n';
cout << "lingling" << endl;
double a = 1;
double b = 2;
cout << a+b <<endl;
return 0;
}
C++标准库
重载左移操作符让程序变得非常的神奇,这种方法非常不错。因此C++的牛人们已经将它完美的实现在C++里面了,实现在哪个地方呢?
就是接下来所要讲的C++标准库中。
C++标准库并不是C++语言的一部分
C++标准库是由类库和函数库组成的集合
C++标准库中定义的类和对象都位于std命名空间中
C++标准库的头文件都不带.h后缀
C++标准库涵盖了C库的功能
C++编译环境的组成
C++扩展语法模块,不同的编译器是不一样的。比如说g++编译器的语法扩展模块与VC++的语法扩展模块肯定是不同的。
但是不管如何的扩展,每个C++编译器生产厂商肯定会支持标准的C++语法,而现在所学习的都是标准的C++语法。
C语言兼容库:使用方式和C语言库是完全一样的
//1.这个地方使用的既不是C++标准库,也不是C语言库,它是C++编译器厂商为了推广自己的产品而提供的C兼容库,
//#include <stdio.h>
//#include <string.h>
//#include <stdlib.h>
//#include <math.h>
//2.使用C++标准库中的C语言兼容模块
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
//注意使用标准库,一定要打开std命名空间
using namespace std;
int main()
{
printf("hello yidaixiaoxiong ,I love you!\n");
char *p = (char*)malloc(16);
strcpy(p,"hello xiaoge");
printf("%s\n",p);
double a = 3;
double b = 4;
double c = sqrt(a * a + b * b);
printf("c = %f\n",c);
free(p);
return 0;
}
#include <iostream>
#include <cmath>
//注意使用标准库,一定要打开std命名空间
using namespace std;
int main()
{
cout << "hello yidaixiaoxiong ,I love you!\n" << 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 << endl;
return 0;
}