实现类模板实现
时间: 2023-11-28 08:47:36 浏览: 49
类模板是一种通用的类定义,其中一些或全部类型是声明(而不是具体的)。类模板的目的是在不重复编写代码的情况下,为不同的类型提供通用的代码。
下面是一个简单的类模板实现的示例:
```cpp
template<class T>
class myClass {
private:
T data;
public:
myClass(T d) : data(d) {}
void printData() { std::cout << data << std::endl; }
};
```
在上面的代码中,`myClass` 是一个类模板,它有一个类型参数 `T`。`T` 可以是任何类型,如 `int`、`double`、`std::string` 等。`myClass` 中有一个私有成员变量 `data`,它是类型为 `T` 的对象。
构造函数 `myClass(T d)` 接受一个类型为 `T` 的参数 `d`,并将其存储在 `data` 中。
成员函数 `printData()` 用于打印存储在 `data` 中的值。
要使用类模板,需要指定类型参数 `T`。例如,以下代码创建了一个 `myClass` 对象,其中类型参数为 `int`:
```cpp
myClass<int> obj(10);
obj.printData(); // 输出 10
```
以下代码创建了一个 `myClass` 对象,其中类型参数为 `std::string`:
```cpp
myClass<std::string> obj("Hello World!");
obj.printData(); // 输出 Hello World!
```
注意,类模板的定义通常包含在头文件中,以便在需要时可以包含它。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)