结构体
具有成员变量和函数的自定义数据类型。有点像对象。。
使用.操作符访问Struct内部变量、函数
可以基于你定义的结构体类型创建(实例化)很多结构体
结构体的定义
定义一个玩家类型,包含成员变量等级、血量、伤害、体力
struct Player
{
int level;
float health;
float damage;
float stamina;
void TakeDamage(float dmg)
{
health -= dmg;
}
int GetLevel()
{
if (level > 10)
{
cout << "level > 10!\n";
}
return level;
}
};
结构体初始化
int main()
{
//创建Player实例
Player player_1;
//初始化
player_1.level = 12;
player_1.health = 100.f;
player_1.damage = 10.f;
player_1.stamina = 20.f;
cout << "player_1 level = " << player_1.GetLevel() << endl;
player_1.TakeDamage(40.f);
cout << "player_1 takes " << 40.f << " damage" << endl;
cout << "player_1 current health: " << player_1.health << endl;
}
使用列表初始化
Player player_2 = {1, 15.f, 40.f, 40.5f};
结构体嵌套
结构体中也可以套结构体!
struct LocationVector
{
float X;
float Y;
float Z;
};
struct Player
{
….
LocationVector location = {0.f, 0.f, 0.f};
…..
void DisplayLocation()
{
cout << location.X << endl;
cout << location.Y << endl;
cout << location.Z << endl;
}
};
嵌套的初始化
Player player_2 = {1, 15.f, 40.f, 40.5f, {1.f,1.f,1.f}};