C++ class templates are a general programming tool that can create classes that can be applied to a variety of data types

C++类模板是一种通用的编程工具,可以创建可以适用于多种数据类型的类。它们允许在类定义中使用参数,以便根据需要实例化具体的类。

使用C++类模板时,首先需要定义模板。模板定义的语法如下:

```cpp
template <typename T>
class MyClass {
    
    
    // 类成员和方法的定义
};

Among them, typename Tis the template parameter, which can be of any type. In a class definition, you can use Tto represent the type.

Next, we can use templates to instantiate concrete class objects. For example, if we want to create a class object that can store integers, we can do this:

MyClass<int> obj1;

In this way, obj1it is an object instantiated with an integer type MyClass.

Method definitions in class templates can be defined inside the class or outside the class. If you choose to define a method outside the class, you can use template<typename T>to indicate that the method belongs to the class template.

Here is an example that demonstrates the use of class templates:

template<typename T>
class MyStack {
    
    
private:
    T* stack;
    int size;
public:
    MyStack() {
    
    
        size = 0;
        stack = new T[100];
    }

    void push(T element) {
    
    
        stack[size++] = element;
    }

    T pop() {
    
    
        return stack[--size];
    }
};

int main() {
    
    
    MyStack<int> stack;
    stack.push(1);
    stack.push(2);
    stack.push(3);

    int val = stack.pop();
    cout << val << endl;  // 输出3

    return 0;
}

In the above example, we defined a MyStackclass template that is used to create a stack that can store any type of data. Then, in mainthe function, we use to MyStack<int>instantiate a stack object that stores integers and perform some operations.

I hope this example can help you understand the use of C++ class templates. If you have any other questions, please feel free to ask!

Guess you like

Origin blog.csdn.net/m0_46376834/article/details/132804348