# Struct
---
當需要處存的資料有非常多的細項且會重複
ex. 遊戲角色 - 需要處存HP、攻擊力、防禦力等
---
宣告
```cpp
struct Player{
string name;
int HP,attack,defense;
};
Player Data;
Data.HP = 100;
```
----
可是這樣只能儲存一位角色
-->用陣列解決! `Player Data[100]`
```cpp
Data[0].HP = 100;//第0位玩家的HP設為100
```
----
怎麼初始化?
```cpp
struct Player{
string name = "";
int HP = 100,attack = 10,defense = 10;
};
```
---
進階用法
----
```cpp
using namespace std;
#define int long long
struct vec{//向量
int x,y,r;
vec(int _x = 0,int _y = 0) : x(_x),y(_y){
r = sqrt(x*x+y*y);
}//建構函數(建構子)
void PrintVec(){
cout<<x<<" "<<y<<" "<<r<<"\n";
}//void函數
int ReturnVec(){
return r;
}//int函數
int ChangeVec(int _x,int _y){
x = _x;y = _y;
r = sqrt(x*x+y*y);
}//void函數
};
signed main(){
vec p1(3,4);
p1.PrintVec();
p1.ChangeVec(5,12);
p1.PrintVec();
int _r = p1.ReturnVec();
cout<<_r;
return 0;
}
```
{"title":"Struct","contributors":"[{\"id\":\"04b05e67-b6a9-4c04-9235-c66acad9fe35\",\"add\":1194,\"del\":320}]"}