namespace std:为了避免标志符冲突
三种使用方式:
直接使用:std::cout << "hello" << std::endl;
先声明后使用:
using std::cout;
using std::endl;
cout << "hello" << endl;
直接声明使用:
std:using namespace std;
cout << "hello" << endl;
头文件:header files
全部都在命名空间std内
#include <iostream> //C++
#include <cstdlib> //C library, is #include <stdlib.h>
#include <string> //C++
#include <cstring> //C
异常处理:
string:异常检查比较严格
STL:求速度忽视异常,只考虑运行期异常
C++语言支持的exception:基类是exception
bad_alloc:new失败的时候抛出 <new>
bad_cast:dynamic_cast失败抛出 <typeinfo>
bad_typeid:typeid运行时类别 <typeinfo>
bad_exception:抛出了未预料的异常 <exception>
标准库异常:基类logic_error,程序中可以避免
invalid_argument:不合法的参数 <stdexcept>
length_error:长度超出最大的限制 <stdexcept>
out_of_range:如数组下标越界 <stdexcept>
domain_error <stdexcept>
IO异常:ios_base::failure <ios>
运行期间异常:继承自runtime_error
range_error:内部指令错误 <stdexcept>
overflow_error:算术溢出 <stdexcept>
underflow_error: <stdexcept>
获取异常额外信息:
what() 函数,返回char*
1
2
3
4
|
try { } catch ( const exception&
e) { std::cout
<< e.what() << std::endl; } |
继承std::exception定义自己的异常类:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
namespace MySpace
{ class MyException
: public std::exception
{ public : MyException(...)
{} virtual const char *
what() const throw ()
{ //... } }; void f()
{ ... throw MyException(...); } } |
内存分配器:负责内存分配和解除分配的对象
默认:new and delete