6. 结构体和自定义类型
结构体与自定义类型
- 结构体:将相关的数据放置在一起
-
可以通过点操作符( . )访问内部元素
-
可以作为函数的输入参数或返回类型
一个简单的代码示例:
// self-defined data type -- struct #include <iostream> struct Point { int x; int y; }; // Point void printPoint(Point p) { std::cout << "x: " << p.x << " y: " << p.y << "\n"; } Point handlePoint(Point p) { p.x = p.x + 1; p.y = p.y + 2; return p; } int main(void) { Point p; p.x = 255; p.y = 0; printPoint(p); auto new_point = handlePoint(p); std::cout << "x: " << new_point.x << " y: " << new_point.y << "\n"; return 0; }
编译运行结果:
> g++ -Wall -g struct.cpp -o struct > ./struct x: 255 y: 0
-
可以引入成员函数,更好地表示函数与数据的相关性
示例代码:
// self-defined data type -- struct #include <iostream> struct Point { int x; int y; void IncP() { // member func: incP x = x + 1; y = y + 1; } }; // Point void printPoint(Point p) { std::cout << "x: " << p.x << " y: " << p.y << "\n"; } int main(void) { Point p; p.x = 255; p.y = 0; printPoint(p); p.incP(); printPoint(p); return 0; }
-