c++标准库

(1)左移、右移操作符重载

 a. 操作符<<的原生意义是按位左移,如 1<< 2

 b. 意义000 0001-> 000 0100

 c. 代码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& operator << (const char* s)

   {

       printf("%s", s);

       return *this;

   }

   Console& operator << (double d)

   {

       printf("%f", d);

       return *this;

   }

};

Console cout;

int main()

{

   cout << 1 << endl;

   cout << "D.T.Software" << endl;

   double a = 0.1;

   double b = 0.2;

   cout << a + b << endl;

   return 0;

}

运行结果:


(2)c++标准库概述

 a. c++标准库不是c++语言的一部分

 b. c++标准库是由类库和函数库组成的集合

 c. 库中定义的类和对象都位于std命名空间中

 d. 库的头文件都不带.h

 e. c++标准库涵盖了c库的功能

(3)C++标准库预定义了多数常用的数据结构



代码2 初探标准库#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);

   

   free(p);

   

   return 0;

}

运行结果:



 (4)标准库使用

 代码3输入输出流使用:

#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;

}


运行结果:



©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容