C++ 数据类型

struct

/**
 * 这里的student相当于一个对象
 * name|age是student的属性
 */
struct student {
  string name;
  int age;
};
//    初始化
student stu1;
student.name = "XiaoMing";
student.age = 18;
// -----------------------------------------
//  指针获取student属性
student *studentPointer = &student;
string name = studentPointer->name;
// -----------------------------------------

 

union:

/**
 * union中的属性共用一个内存
 * 例:当i=97时,输出的c 为'a'
 */
union myType {
  int i;
  char c;
};
// -----------------------------------------
/**
 * 在struct结构体中,可以匿名使用union
 */
struct book {
  char title[50];
  char author[50];
  union {
    float dollars;
    int yen;
  }
};
//  获取book中的匿名属性
book book1;
book1.dollars;
// -----------------------------------------

 

enum:

/**
 * 常规枚举
 * 若不设置black值,则会默认0;后续值为前一个+1
 */
enum colors_t {
  black=1,
  blue,
  green
};
//  枚举使用
colors_t myColor = blue;
cout << myColor << endl;  // 输出对应的指为2
// -----------------------------------------
/**
 * class类型的枚举
 */
enum class Colors {
  black,
  blue,
  green
};
//  enum class 使用
Colors myColor = Colors::black;
// -----------------------------------------
/**
 * 枚举指定基础类型
 * todo 还不太确定这个有什么用
 */
enum class EyeColor : char {
  blue,
  green,
  brown
}

 

posted @ 2023-08-31 23:11  水水君  阅读(3)  评论(0编辑  收藏  举报