1.struct
结构体(struct)是根据自己的需要,而定义的变量集合
1.1 struct的定义
第一种:
struct Student
{
std::string m_name;
int32_t m_age;
float m_score;
};
//使用
struct Student stu;
第二种(不建议使用):
struct Student
{
std::string m_name;
int32_t m_age;
float m_score;
}Stu;
struct
{
std::string m_name;
int32_t m_age;
float m_score;
}Stu;
//使用,上述只是定义了一个结构体变量Stu
第三种(一般使用这种):
通过 typedef 关键字来定义结构体的别名,方便后续的使用
typedef struct Student
{
std::string m_name;
int32_t m_age;
float m_score;
}Stu;
typedef struct
{
std::string m_name;
int32_t m_age;
float m_score;
}Stu;
//使用
Stu stu;
1.2 初始化
第一种:
结构体的构造函数初始化,一般建议初始化,防止出现垃圾数据
typedef struct Student
{
std::string m_name;
int32_t m_age;
float m_score;
Student()
{
m_name = "";
m_age = -1;
m_score = -0.0;
}
}Stu;
//使用
Stu stu;
第二种:
typedef struct Student
{
std::string m_name;
int32_t m_age;
float m_score;
Student(std::string name,int32_t age,float score):m_name(name),m_age(age),m_score(score){}
}Stu;
//使用
Stu stu("wang",18,98);
2. 运算符重载
第一种:
typedef struct Student
{
std::string m_name;
int32_t m_age;
float m_score;
Student(std::string name,int32_t age,float score):m_name(name),m_age(age),m_score(score){}
friend bool operator < (struct Student s1, struct Student s2){
return s1.m_score < s2.m_score;
}
}Stu;
使用:
Stu stu1("wang",18,98);
Stu stu2("li",18,100);
if(stu1 < stu2){
cout<<"stu1 has many score";
}
else{
cout<<"stu2 has many score";
}
第二种:
无friend
typedef struct Student
{
std::string m_name;
int32_t m_age;
float m_score;
Student(std::string name,int32_t age,float score):m_name(name),m_age(age),m_score(score){}
bool operator < (struct Student s1) const {
return s1.m_score < m_score;
}
}Stu;
使用同方法一
3. enum
第一种:
定义
enum Color
{
black,
white,
red
};
使用
int main()
{
Color a = Color::white;
cout<<Color::black<<endl;
cout<<a<<endl; //支持隐式转换
return 0;
}
该种方法会污染外部的作用域,以下使用会报错,在同一作用域下,变量重复定义
/*
以下操作不允许
enum Color
{
black,
white,
red
};
enum Color_Car
{
black,
white,
red
};
*/
第二种:
enum class
定义:
enum class Color
{
black,
white,
red
};
使用:
int main()
{
Color a = Color::white;
cout<<(int)a<<endl; //不支持隐式转换
return 0;
}
enum class 不会污染作用域
enum class Color
{
black = 1,
white,
red
};
enum class Color_Car
{
black = 20,
white,
red
};
使用
int main()
{
cout<<"Color::black is: "<<(int)Color::black<<endl;
cout<<"Color_Car::black is: "<<(int)Color_Car::black<<endl;
return 0;
}
输出:
Color::black is: 1
Color_Car::black is: 20