模板:
函数模板:
template <typename type>ret-type func-name(parameter list)
{
// 函数的主体
}
e.g.
template <typename T>
T add(T a, T b)
{
return a + b;
}
cout << add(3, 6) <<endl;
cout << add(1.1, 2.2) <<endl;
类模板:
template <class type> classclass-name {
…
};
e.g.
template <class T>
class Stack{
private:
vector<T> elems;
public:
void push(T const&);
void pop();
T top() const;
bool empty(){
return elems.empty();
}
};
template <class T>
void Stack<T>::push (Tconst& elem)
{
elems.push_back(elem);
}
template <class T>
void Stack<T>::pop()
{
if (elems.empty())
{
throw out_of_range("Emptystack.");
}
elems.pop_back();
}
template <class T>
T Stack<T>::top() const
{
if (elems.empty())
{
throw out_of_range("Emptystack.");
}
return elems.back();
}
tips:
关于成员函数const关键字的说明:
|
预处理器:
预处理器是一些指令,指示编译器在实际编译之前所需完成的预处理。
所有的预处理器指令都是以井号(#)开头,只有空格字符可以出现在预处理指令之前。预处理指令不是 C++ 语句,所以它们不会以分号(;)结尾。
预处理的几个示例:
1. 预定义常量:
#define PI 3.1415
2. 预定义方法:
#define ADD(a,b) a+b
3. 定义DEBUG信息
#define DEBUG
#ifdef DEBUG
cerr << "Debugginginformation" << endl;
#endif
4. 取消某个定义
#undef DEBUG
5. 组合条件判断
#define DEBUG
#define ERROR
#if defined(DEBUG) && (defined(ERROR) || defined(WARN))
cerr << "Warning:blablabla" << endl;
#endif
6. 条件分支
#ifndef INFO
#define INFO 1
#else
#undef INFO
#define INFO 1
#endif
7. 注释掉部分语句使其不参与编译
#if 0
//code will not be compiled
#endif
8. # 运算符会把replacement-text 令牌转换为用引号引起来的字符串,例如:
#define MKSTR( x ) #x
9. ## 运算符用于连接两个令牌,将结果转换为字符串,例如:
#define CONCAT( x, y ) x ## y
C++中预定义的宏:
宏 |
描述 |
__LINE__ |
这会在程序编译时包含当前行号。 |
__FILE__ |
这会在程序编译时包含当前文件名。 |
__DATE__ |
这会包含一个形式为 month/day/year 的字符串,它表示把源文件转换为目标代码的日期。 |
__TIME__ |
这会包含一个形式为 hour:minute:second 的字符串,它表示程序被编译的时间。 |
e.g.
cout <<"Value of __LINE__ : " << __LINE__ << endl;
cout <<"Value of __FILE__ : " << __FILE__ << endl;
cout <<"Value of __DATE__ : " << __DATE__ << endl;
cout <<"Value of __TIME__ : " << __TIME__ << endl;
信号处理:
信号是由操作系统传给进程的中断,会提早终止一个程序。例如在 UNIX、LINUX、Mac OS X 或 Windows 系统上,可以通过按 Ctrl+C 产生中断。有些信号不能被程序捕获,但是下表所列信号可以在程序中捕获,并可以基于信号采取适当的动作。这些信号是定义在 C++ 头文件 <csignal> 中。
信号 |
描述 |
SIGABRT |
程序的异常终止,如调用 abort。 |
SIGFPE |
错误的算术运算,比如除以零或导致溢出的操作。 |
SIGILL |
检测非法指令。 |
SIGINT |
接收到交互注意信号。 |
SIGSEGV |
非法访问内存。 |
SIGTERM |
发送到程序的终止请求。 |
C++ 信号处理库提供了 signal 函数,用来捕获突发事件。signal() 函数的定义:
void (*signal (intsig, void (*func)(int)))(int);
这个函数接收两个参数:第一个参数是一个整数,代表了信号的编号;第二个参数是一个指向信号处理函数的指针。
e.g.
void signalHandler(int sig)
{
cout << "Interrupt signal (" << sig <<") received.\n";
exit(sig);
}
signal(SIGINT, signalHandler);
while (true)
{
cout << "#";
for (int i = 0; i < 10000000; i++) { }
}
可以使用raise函数来生成一个signal,raise()函数的定义:
int raise (signalsig);
e.g.
raise(SIGINT);