初遇c++结构, 联合, 枚举

结构:

#include <iostream>

int main(void) {
  // c语言声明结构, 需要用typedef定义名字:
  typedef struct my_wife {
    std::string wife1;
    std::string wife2;
    std::string wife3;
  } my_wife;
  my_wife wifes{"一花", "二乃", "三玖"};
  std::cout << wifes.wife1 << '\t' << wifes.wife2 << '\t' << wifes.wife3
            << '\n';

  // c++ 声明结构, 可以直接初始化就行, 不需要用typedef来另起名字:
  struct lin_wife {
    std::string wife1;
    std::string wife2;
    std::string wife3;
  };
  lin_wife wifex{"北白川玉子", "古贺-唯花", "呆唯"};
  std::cout << wifex.wife1 << '\t' << wifex.wife2 << '\t' << wifex.wife3
            << '\n';

  // c++ 还支持同类型的成员直接(赋值)复制:
  lin_wife wife_x = wifex;
  std::cout << wife_x.wife1 << '\t' << wife_x.wife2 << '\t' << wife_x.wife3
            << '\n';
}

联合:

#include <iostream>

int main(void) {
  // 联合类型, 一次只能存一个, 但中途可以改变内容, 但无论何时,
  // 内部都只有一个数据
  union number {
    int digit;
    // std::string str_num;
    char str_num[50];
  };

  // 声明如下:
  number num;
  num.digit = {520};
  std::cout << num.digit << '\n';

  std::cin.getline(num.str_num, 50);
  std::cout << num.str_num << std::endl;

  return 0;
}

枚举:

#include <iostream>

int main(void) {
  std::cout << false << '\t' << true << std::endl;

  // 枚举类型:
  enum color { black, white };
  std::cout << black << '\t' << white << '\n';

  color blc_wit;
  std::cout << blc_wit << '\t';

  blc_wit = white;
  std::cout << blc_wit << '\n';

  // 最多只能赋值枚举里面的最大值!
  blc_wit = 2000;
  std::cout << blc_wit << '\n';

  return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值