struct
定义
struct person
{
std::string name{"Haymax"};
int age=18;
};
//也可以声明没有名字的结构体类型,直接构建一个这种类型的变量
struct
{
std::string name{"Haymax"};
int age=18;
} candidate0;
//结构体也有构造函数和析构函数
struct Node{
int value;
Node *next;
Node *father;
// 构造函数,构造node的时候被调用,大括号不能省略
Node():value(1), next(nullptr), father(nullptr){};
// 默认构造函数和构造函数重载;
Node(int v, Node *next_){
std::cout<<"v is "<<v<<std::endl;
value = v;
father = new Node;
next = next_;
};
~Node(){
std::cout<<"deleting"<<std::endl;
delete father;
};
};
声明
person candidate0 = {"Haymax", 18};
结构体也可以使用相应的列表初始化的方式来初始化。
enum
定义
enum pets {cat, dog, bird, fish};
enum pets {cat, dog, bird=5, fish}; //fish会接着向后数,在这里就是6
使用
pets my_pet;
!注意,枚举类型可以在自动类型转换的过程中转换成int,但是不能直接当int用。