笨蛋学C++【C++基础第九弹】

发布于:2024-05-06 ⋅ 阅读:(27) ⋅ 点赞:(0)

5.C++模板

  • 模板是泛型编程的基础,泛型编程即以一种独立于任何特定类型的方式编写代码

函数模板

  • 语法:

    template <typename type> 返回的数据类型 函数名(相关参数){
        函数部分代码
    }
    //声明函数模板
    template <typename T>
    void swap(T &a,T &b){
        T temp = a;
        a = b;
        b = temp;
    }
    
    //调用
    swap(10,20)
    swap<int>(a,b);
    
    //
    // Created by 16690 on 2024/4/22.
    //
    
    #include <iostream>
    
    using namespace std;
    
    template<typename T>
    inline T const &Max(T const &a, T const &b) {
        return a < b ? b : a;
    }
    
    int main(void) {
    
        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;
    
        char c1 = 'a';
        char c2 = 'b';
        cout << "Max(c1,c2):" << Max(c1, c2) << endl;
    
        return 0;
    }
    

类模板

  • 语法

    template <class type> class 类名{
        类代码说明
    }
    
    #include <iostream>
    #include <vector>
    #include <cstdlib>
    #include <string>
    #include <stdexcept>
     
    using namespace std;
     
    template <class T>
    class Stack { 
      private: 
        vector<T> elems;     // 元素 
     
      public: 
        void push(T const&);  // 入栈
        void pop();               // 出栈
        T top() const;            // 返回栈顶元素
        bool empty() const{       // 如果为空则返回真。
            return elems.empty(); 
        } 
    }; 
     
    template <class T>
    void Stack<T>::push (T const& elem) 
    { 
        // 追加传入元素的副本
        elems.push_back(elem);    
    } 
     
    template <class T>
    void Stack<T>::pop () 
    { 
        if (elems.empty()) { 
            throw out_of_range("Stack<>::pop(): empty stack"); 
        }
        // 删除最后一个元素
        elems.pop_back();         
    } 
     
    template <class T>
    T Stack<T>::top () const 
    { 
        if (elems.empty()) { 
            throw out_of_range("Stack<>::top(): empty stack"); 
        }
        // 返回最后一个元素的副本 
        return elems.back();      
    } 
     
    int main() 
    { 
        try { 
            Stack<int>         intStack;  // int 类型的栈 
            Stack<string> stringStack;    // string 类型的栈 
     
            // 操作 int 类型的栈 
            intStack.push(7); 
            cout << intStack.top() <<endl; 
     
            // 操作 string 类型的栈 
            stringStack.push("hello"); 
            cout << stringStack.top() << std::endl; 
            stringStack.pop(); 
            stringStack.pop(); 
        } 
        catch (exception const& ex) { 
            cerr << "Exception: " << ex.what() <<endl; 
            return -1;
        } 
    }
    

6.C++预处理器

  • 预处理器是一些指令,指示编译器在实际编译之前所需完成的预处理
  • 所有的预处理器指令都是以井号(#)开头,只有空格字符可以出现在预处理指令之前。
  • 预处理指令不是 C++ 语句,所以它们不会以分号(;)结尾。

#define 预处理

  • #define 预处理指令用于创建符号常量,该符号常量通常称为

  • 语法:

    #define 常量名 常量值
    
    #include <iostream>
    using namespace std;
     
    #define PI 3.14159
     
    int main ()
    {
     
        cout << "Value of PI :" << PI << endl; 
     
        return 0;
    }
    

参数宏

//
// Created by 16690 on 2024/4/22.
//

#include <iostream>
using namespace std;

#define MIN(a,b) (a<b ? a:b)
int main(void){

    int i,j;
    i=100;
    j=30;
    cout << "MIN(i,j) = " << MIN(i,j) << endl;

    return 0;
}

条件编译

  • 有几个指令可以用来有选择地对部分程序源代码进行编译

    #ifdef NULL
    	#define NULL 0 
    #endif
    
    #ifdef DEBUG
    	cerr << "Variable x = " << x <<endl;
    #endif
    
  • 如果在指令 #ifdef DEBUG 之前已经定义了符号常量 DEBUG,则会对程序中的 cerr 语句进行编译

    #if 0
       不进行编译的代码
    #endif
    
    #include <iostream>
    using namespace std;
    #define DEBUG
     
    #define MIN(a,b) (((a)<(b)) ? a : b)
     
    int main ()
    {
       int i, j;
       i = 100;
       j = 30;
    #ifdef DEBUG
       cerr <<"Trace: Inside main function" << endl;
    #endif
     
    #if 0
       /* 这是注释部分 */
       cout << MKSTR(HELLO C++) << endl;
    #endif
     
       cout <<"The minimum is " << MIN(i, j) << endl;
     
    #ifdef DEBUG
       cerr <<"Trace: Coming out of main function" << endl;
    #endif
        return 0;
    }
    

# 和 ## 运算符

  • # 运算符用于将宏的参数转换为一个字符串字面量

  • ## 运算符用于在预处理阶段将两个标记(tokens)连接为一个

//
// Created by 16690 on 2024/4/22.
//
#include <iostream>
#include <stdio.h>
using namespace std;

#define STRING(x) #x #x #x
#define TEXT(x) "class"#x"Info"

#define CONCAT(x, y) x ## y

int main ()
{
    int abc = 100;
    cout << "STRING(abc)=" << STRING(abc) << endl;
    cout << "TEXT(x)=" << TEXT(abc) << endl;

    int xy =100;
    cout << CONCAT(x,y) << endl;
    //将cout << CONCAT(x,y) << endl;转为cout << xy

    int test = 222;
    cout << CONCAT(tes,t) << endl;
    
    return 0;
}

C++ 中的预定义宏

描述
LINE 这会在程序编译时包含当前行号。
FILE 这会在程序编译时包含当前文件名。
DATE 这会包含一个形式为 month/day/year 的字符串,它表示把源文件转换为目标代码的日期。
TIME 这会包含一个形式为 hour:minute:second 的字符串,它表示程序被编译的时间。
#include <iostream>
using namespace std;
 
int main ()
{
    cout << "Value of __LINE__ : " << __LINE__ << endl;
    cout << "Value of __FILE__ : " << __FILE__ << endl;
    cout << "Value of __DATE__ : " << __DATE__ << endl;
    cout << "Value of __TIME__ : " << __TIME__ << endl;
 
    return 0;
}

7.C++信号处理

  • 信号是由操作系统传给进程的中断,会提早终止一个程序

    信号 描述
    SIGABRT 程序的异常终止,如调用 abort
    SIGFPE 错误的算术运算,比如除以零或导致溢出的操作。
    SIGILL 检测非法指令。
    SIGINT 程序终止(interrupt)信号。
    SIGSEGV 非法访问内存。
    SIGTERM 发送到程序的终止请求。

signal() 函数

C++ 信号处理库提供了 signal 函数,用来捕获突发事件。以下是 signal() 函数的语法:

void (*signal (int sig, void (*func)(int)))(int); 

以下语法格式更容易理解:

signal(registered signal, signal handler)
  • 第一个参数是要设置的信号的标识符,第二个参数是指向信号处理函数的指针。
  • 函数返回值是一个指向先前信号处理函数的指针。如果先前没有设置信号处理函数,则返回值为 SIG_DFL。如果先前设置的信号处理函数为 SIG_IGN,则返回值为 SIG_IGN。‘
//
// Created by 16690 on 2024/4/23.
//
#include <iostream>
#include <csignal>
#include <unistd.h>
using namespace std;
void signalHandler(int signum){
    cout << "Interrupt signal (" << signum << ") received.\n";

    exit(signum);
}
int main(void){

    ::signal(SIGINT,signalHandler);

    while(1){
        cout << "Going to sleep...." << endl;
        sleep(1);
    }
    return 0;
}

raise() 函数

  • 使用函数raise()生成信号,该函数带有一个整数信号编号作为参数

    int raise(signal sig);
    
    //
    // Created by 16690 on 2024/4/23.
    //
    #include <iostream>
    #include <csignal>
    #include <unistd.h>
    using namespace std;
    void signalHandler(int signum){
        cout << "Interrupt signal (" << signum << ") received.\n";
    
        exit(signum);
    }
    int main(void){
    
        signal(SIGINT,signalHandler);
    
        int i=0;
        while(++i){
            cout << "Going to sleep...." << endl;
    
            while(++i){
                raise(SIGINT);
            }
            sleep(1);
        }
        return 0;
    }