做网站视频上传到哪儿上海seo推广公司
c++ 类模板
文章目录
- c++ 类模板
- C++ 类模板概念
- 类模板语法结构:
- 示例:泛型容器类
- 类模板的优势
- 小结
C++ 类模板概念
类模板是 C++ 提供的一种泛型编程机制,用于编写可以处理多种数据类型的类,而不用为每种类型都写一个类。
模板 = 写一次代码,适配多种类型
类模板语法结构:
template <typename T>
class MyClass {
public:T value;MyClass(T v) : value(v) {}void printInfo() {std::cout << "Value: " << value << std::endl;}
};
这里 T
就是一个类型参数,在使用时可以替换为 int
、float
、std::string
等。
示例:泛型容器类
#include <iostream>
#include <string>template <typename T>
class Box {
public:Box(T item) : content(item) {}void show() {std::cout << "Box contains: " << content << std::endl;}private:T content;
};int main() {Box<int> intBox(123);Box<std::string> strBox("Hello, Template!");intBox.show(); // 终端会输出:Box contains: 123strBox.show(); // 终端会输出:Box contains: Hello, Template!return 0;
}
类模板的优势
优势 | 说明 |
---|---|
类型通用 | 不再为每种类型写重复代码 |
更安全 | 编译期类型检查,避免手动 void* |
易扩展 | 只需扩展接口即可自动支持新类型 |
小结
template <typename T>
:声明类是模板类,T
是类型参数- 使用时:
Box<int>
,Box<std::string>
这样的实例化 - 类模板可以有多个类型参数:
template <typename T, typename U>