一杯清酒邀明月
天下本无事,庸人扰之而烦耳。

内联函数从源代码层看,有函数的结构,而在编译后,却不具备函数的性质。编译时类似宏替换,使用函数体替换调用处的函数名。(在程序中,调用其函数时,该函数在编译时被替换,而不是像一般函数那样是在运行时被调用)

实例:栈

 1 #include <iostream>
 2 #include <string>
 3 
 4 template <class T>
 5 class Stack//栈类 
 6 {
 7 public:
 8     Stack(unsigned int size = 100)//构造器 
 9     {
10         this->size = size;
11         data = new T(size);
12         sp = 0;
13     } 
14     ~Stack()//析构器
15     {
16         delete []data;//删除数组
17     } 
18     void push(T value)//入栈
19     {
20         data[sp++] = value;
21     } 
22     T pop()//出栈
23     {
24         return data[--sp];
25     }
26 private:
27     unsigned int size;
28     unsigned int sp;
29     T *data; 
30 };
31 
32 int main()
33 {
34     Stack<int> intStack(100);//定义对象 
35     
36     intStack.push(1);//将1推入栈 
37     intStack.push(2);//将2推入栈
38     intStack.push(3);//将3推入栈
39     
40     std::cout << intStack.pop() << "\n";//弹栈
41     std::cout << intStack.pop() << "\n";//弹栈
42     std::cout << intStack.pop() << "\n";//弹栈
43 }

如果类模板需要一种以上的类型,可根据具体情况多使用几个占位符

1 template<class T,class U>
2 
3 class MyClass
4 {
5 //
6 }

实例化(即定义对象)时:

MyClass<int,float>myClass;
posted on 2023-08-18 15:39  一杯清酒邀明月  阅读(39)  评论(0编辑  收藏  举报