一般概念
1、命名空间
C++标准程序库中的所有标识符都被定义于一个名为std的namespace中
使用C++标准程序库的任何标识符时,有3种选择
(1)、直接指定
例如:std::cout<<3<<std::endl;
(2)、使用using declaration
例如:
using std::cout;
using std::endl;
(3)、使用using directive
例如:`using namespace std;`
2、头文件
引入如下风格的头文件:
#include<iostream>
#include<string>
#include<stdlib.h> == #include<cstdlib>
3、错误处理与异常处理
标准异常分类:
(1)、语言本身支持的异常
bad_alloc(new失败)
bad_cast(动态转换操作失败)
bad_typeid(交给typeid的参数为0或空指针时)
如果发生非预期的异常,bad_exception异常会接受处理,调用unexpected()
例如:
class E1;
class E2;
void f() throw(E1) //throws only exceptions of type E1
{
throw E1();
throw E2(); //calls unexpected(),which calls terminate()终止程序
}
如果在异常规格中列出bad_exception,那么unexpected()将重新抛出bad_exception异常
例如:
class E1;
class E2;
void f() throw(E1,std::bad_exception) //throws only exceptions of type E1
{
throw E1();
throw E2(); //calls unexpected(),which throws bad_exception
}
(2)、C++标准程序库发出的异常
invalid_argument 表示无效参数,例如将bitset以char而不是bit初始化
length_error 指出某个行为“可能超越了最大极限”
out_of_range 指出参数值“不在预期范围内”,例如在array或string中采用了错误索引
domain_error
(3)、程序作用域之外发出的异常
异常类的成员
namespace std{
class exception{
public:
virtual const char* what const throw();
}
}
接口只含一个成员函数what(),返回的字符串为一些信息
打印信息:
try {
}
catch(const std:exception& error){
std:cerr<<error.what()<<std::endl;
}
4、配置器
C++标准程序库在许多地方采用特殊对象来处理内存配置和寻址,这样的对象称为allocators(配置器)。它体现出了一种特定的内存模型。使得诸如共享内存,垃圾回收,面向对象数据库等特定内存模型能够保持一致的接口