C语言中结构体和类的区别及使用场景是什么?
结构体基本概念:
-
结构体定义
cstruct Point { int x; int y; }; struct Point p1 = {10, 20}; struct Point p2 = {.x = 30, .y = 40}; -
结构体指针
cstruct Point *ptr = &p1; ptr->x = 50; ptr->y = 60;
与类的对比:
-
数据封装
c// C语言结构体 struct Rectangle { int width; int height; }; // C++类 class Rectangle { private: int width; int height; public: Rectangle(int w, int h) : width(w), height(h) {} int area() { return width * height; } }; -
方法定义
c// C语言:使用函数指针 struct Shape { int (*area)(struct Shape*); int (*perimeter)(struct Shape*); }; int rectangle_area(struct Shape *s) { struct Rectangle *r = (struct Rectangle*)s; return r->width * r->height; } // C++:成员函数 class Shape { public: virtual int area() = 0; virtual int perimeter() = 0; }; -
构造和析构
c// C语言:手动初始化 struct Point create_point(int x, int y) { struct Point p = {x, y}; return p; } void destroy_point(struct Point *p) { // 手动清理资源 } // C++:自动构造和析构 class Point { public: Point(int x, int y) : x(x), y(y) {} ~Point() {} private: int x, y; };
使用场景:
-
数据结构
cstruct Node { int data; struct Node *next; }; struct LinkedList { struct Node *head; int size; }; -
配置管理
cstruct Config { char server[256]; int port; int timeout; int max_connections; }; struct Config load_config(const char *filename); -
网络协议
cstruct PacketHeader { unsigned int version : 4; unsigned int type : 4; unsigned int length : 16; unsigned int checksum : 8; };
高级特性:
-
结构体嵌套
cstruct Address { char street[100]; char city[50]; char country[50]; }; struct Person { char name[50]; int age; struct Address address; }; struct Person person = { .name = "John Doe", .age = 30, .address = { .street = "123 Main St", .city = "New York", .country = "USA" } }; -
结构体数组
cstruct Student { int id; char name[50]; float score; }; struct Student students[100]; students[0].id = 1; strcpy(students[0].name, "Alice"); students[0].score = 95.5; -
灵活数组成员
cstruct String { size_t length; char data[]; // 灵活数组成员 }; struct String *create_string(const char *str) { size_t len = strlen(str); struct String *s = malloc(sizeof(struct String) + len + 1); s->length = len; strcpy(s->data, str); return s; }
最佳实践:
-
命名约定
cstruct Point { int x; int y; }; typedef struct Point Point; Point p1 = {10, 20}; -
初始化函数
cstruct Point point_create(int x, int y) { struct Point p = {x, y}; return p; } struct Point p = point_create(10, 20); -
内存管理
cstruct Point *point_alloc(int x, int y) { struct Point *p = malloc(sizeof(struct Point)); if (p) { p->x = x; p->y = y; } return p; } void point_free(struct Point *p) { free(p); }
注意事项:
-
内存对齐
cstruct Example { char c; // 1字节 + 3字节填充 int i; // 4字节 }; // 总大小: 8字节 -
结构体赋值
cstruct Point p1 = {10, 20}; struct Point p2 = p1; // 浅拷贝 -
结构体比较
cstruct Point p1 = {10, 20}; struct Point p2 = {10, 20}; // 错误:不能直接比较结构体 // if (p1 == p2) { } // 正确:逐个成员比较 if (p1.x == p2.x && p1.y == p2.y) { printf("Equal\n"); }