语句
switch
- 内部变量定义,使用花括号;只定义在该块内
try语句块和异常处理
- throw表达式
- try{…}catch(runtime_error e){…}
标准异常
-
excception:头文件中定义了通用的异常类exception。只报告异常的发生,不提供额外的信息
-
stdexcept:定义了集中常用的异常类
-
new头文件定义了bad_alloc
-
type_info头文件定义了bad_cast异常类型
-
异常类型只有一个what成员函数,返回值是一个C风格字符串
Header guards(include guard)
- 避免一个头文件被多次引用
int getSquareSides() // from square.h
{
return 4;
}
int getSquareSides() // from wave.h (via square.h)
{
return 4;
}
int main()
{
return 0;
}#ifndef SOME_UNIQUE_NAME_HERE
#define SOME_UNIQUE_NAME_HERE
// your declarations (and certain types of definitions) here
#endifHeader guards do not prevent a header from being included once into different code files
-
如果在头文件进行函数定义,如果有多个源文件可能造成链接失败,多次定义同一个函数
-
The best way to work around this issue is simply to put the function definition in one of the .cpp files so that the header just contains a forward declaration:
-
Now when the program is compiled, function getSquareSides will have just one definition (via square.cpp), so the linker is happy. File main.cpp is able to call this function (even though it lives in square.cpp) because it includes square.h, which has a forward declaration for the function (the linker will connect the call to getSquareSides from main.cpp to the definition of getSquareSides in square.cpp).