C++ 提供了多种数据类型组合方式,允许开发者将基本类型组合成更复杂的数据结构,以满足不同场景的需求。以下是主要的组合方式及其示例:
1. 数组(Array)
- 同类型元素的集合,可以是静态或动态。
int staticArray[5] = {1, 2, 3, 4, 5}; // 静态数组
int* dynamicArray = new int[10]; // 动态数组(需手动释放)
2. 结构体(struct)
- 不同类型数据的组合,默认成员为
public
。
struct Student {
std::string name;
int age;
float gpa;
};
Student s {"Alice", 20, 3.8};
3. 类(class)
- 封装数据与方法的类型,默认成员为
private
。
class Rectangle {
int width, height;
public:
Rectangle(int w, int h) : width(w), height(h) {}
int area() { return width * height; }
};
Rectangle rect(3, 4);
4. 联合体(union)
- 共享内存的不同类型,同一时间只能使用一个成员。
union Data {
int i;
float f;
char c;
};
Data d;
d.i = 42; // 此时只能访问 d.i
5. 枚举(enum 和 enum class)
- 命名常量集合,
enum class
提供更强类型检查。
enum Color { Red, Green, Blue }; // 传统枚举
enum class Mode { Read, Write, Execute }; // 枚举类(C++11)
Color c = Green;
Mode m = Mode::Read;
6. 指针与引用
- 间接访问其他数据,常用于动态内存管理。
int x = 10;
int* ptr = &x; // 指针
int& ref = x; // 引用
7. 标准库容器
- 模板化的数据结构,如
vector
,map
,pair
等。
#include <vector>
#include <map>
#include <tuple>
std::vector<int> numbers = {1, 2, 3}; // 动态数组
std::map<std::string, int> ages = {{"Alice", 30}}; // 键值对
auto person = std::make_tuple("Bob", 25, true); // 多元组
8. 类型别名(typedef/using)
- 简化复杂类型声明。
typedef std::vector<std::string> StringList; // C 风格
using StudentVector = std::vector<Student>; // C++11
9. 多维数组
- 数组的数组,常用于矩阵。
int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}};
10. 嵌套组合
- 类型之间的嵌套使用,如结构体包含容器。
struct Classroom {
std::string className;
std::vector<Student> students;
};
Classroom cs101 {"CS101", {{"Alice", 20}, {"Bob", 21}}};
关键注意事项:
- 内存管理:动态数组需用
delete[]
释放,或优先使用智能指针(如std::unique_ptr
)。 - 访问权限:类成员默认
private
,结构体默认public
。 - 类型安全:
enum class
比传统enum
更安全,避免隐式转换。 - 标准库选择:根据需求选择容器(如
vector
随机访问快,list
插入快)。
示例:综合应用
#include <iostream>
#include <vector>
// 结构体定义
struct Point {
int x, y;
};
// 类定义
class Shape {
private:
std::vector<Point> vertices;
public:
void addVertex(Point p) {
vertices.push_back(p);
}
void printVertices() {
for (const auto& p : vertices) {
std::cout << "(" << p.x << ", " << p.y << ")\n";
}
}
};
int main() {
Shape triangle;
triangle.addVertex({0, 0});
triangle.addVertex({1, 0});
triangle.addVertex({0, 1});
triangle.printVertices();
return 0;
}
输出:
(0, 0)
(1, 0)
(0, 1)
通过灵活组合这些数据类型,可以构建出高效、易维护的复杂程序结构。