C++中的结构体写法,用关键字“struct”来包装,如:“struct Rectangle{}”;这里就定义了长方体“Rectangle”结构体,然后在里面定义宽“width”和高“height”成员属性如下:

C++代码  复制
//结构体
struct Rectangle
{
 int width;
 int height;
};

结构体和swap()函数:在main()函数中实例化“Rectangle box1 = { 80,50 };Rectangle box2 = { 100,60 };”,然后“ swap(box1, box2);”将结构体box1和box2互换值输出。

C++代码  复制
int main()
{
 //初始华结构体
 Rectangle box1 = { 80,50 };
 Rectangle box2 = { 100,60 };
 swap(box1, box2);//将结构体box1和box2互换值
 printf("box1宽高:\nbox1.width: %d\nbox1.height: %d\n\n", box1.width, box1.height);
 printf("box2宽高:\nbox2.width: %d\nbox2.height: %d\n\n", box2.width, box2.height);
 cout << "\nPress any key to exit...";
}

输出结果:

C++结构体还需要注意:不能直接在结构体内部复制。