c++基础学习(11)--(模板、预处理器、信号处理)
生活随笔
收集整理的這篇文章主要介紹了
c++基础学习(11)--(模板、预处理器、信号处理)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- 目錄
- 1.模板
- 2.預處理器
- 3.信號處理
目錄
1.模板
模板是泛型編程的基礎,泛型編程:以一種獨立于任何特定類型的方式
#include <iostream> #include <string>using namespace std;template <typename T> inline T const& Max(T const &a , T const &b){return a<b?b:a; }int main(){int i = 10 , j = 11;cout<<"int\t"<<Max(i,j)<<endl;double m = 13.5 , n = 11.3;cout<<"double\t"<<Max(m,n)<<endl;string s1 = "wfy", s2 = "hxm";cout<<"string\t"<<Max(s1,s2)<<endl;return 0; }int 11
double 13.5
string wfy
當上面的代碼被編譯和執行時,它會產生下列結果:
7
hello
Exception: Stack<>::pop(): empty stack
第一個例子中typename改為class也是可以的:
#include <iostream> #include <string>using namespace std;template <class T> inline T const& Max (T const& a, T const& b) { return a < b ? b:a; } int main () {int i = 39;int j = 20;cout << "Max(i, j): " << Max(i, j) << endl; double f1 = 13.5; double f2 = 20.7; cout << "Max(f1, f2): " << Max(f1, f2) << endl; string s1 = "Hello"; string s2 = "World"; cout << "Max(s1, s2): " << Max(s1, s2) << endl; return 0; }Max(i, j): 39
Max(f1, f2): 20.7
Max(s1, s2): World
2.預處理器
3.信號處理
#include <iostream> #include <csignal> #include <unistd.h>using namespace std;void signalHandler( int signum ) {cout << "Interrupt signal (" << signum << ") received.\n";// 清理并關閉// 終止程序 exit(signum); }int main () {// 注冊信號 SIGINT 和信號處理程序signal(SIGINT, signalHandler); while(1){cout << "Going to sleep...." << endl;sleep(1);}return 0; }當上面的代碼被編譯和執行時,它會產生下列結果
Going to sleep…
Going to sleep…
Going to sleep…
現在,按 Ctrl+C 來中斷程序,您會看到程序捕獲信號,程序打印如下內容并退出:
Going to sleep…
Going to sleep…
Going to sleep…
Interrupt signal (2) received.
當上面的代碼被編譯和執行時,它會產生下列結果,并會自動退出:
Going to sleep…
Going to sleep…
Going to sleep…
Interrupt signal (2) received.
總結
以上是生活随笔為你收集整理的c++基础学习(11)--(模板、预处理器、信号处理)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 我们边吃曲奇边聊——Cookie与Ses
- 下一篇: python模块(4)-Collecti