c++代码日记

本文介绍了C++11引入的强类型枚举`enum class`,强调了其类型安全特性,以及如何通过`static_cast`进行显式转换。同时,文章提及了`stringstream`的使用,特别是在解析命令行参数时,如何读取多个值并将其转换为特定类型。
摘要由CSDN通过智能技术生成

enum class

今天遇到:

enum class Mode { Standard, Image, Video };

enum class是强类型枚举 。

在标准C++中,枚举类型不是类型安全的。枚举类型被视为整数,这使得两种不同的枚举类型之间可以进行比较。C++03 唯一提供的安全机制是一个整数或一个枚举型值不能隐式转换到另一个枚举别型。 此外,枚举所使用整数类型及其大小都由实现方法定义,皆无法明确指定。 最后,枚举的名称全数暴露于一般范围中,因此C++03两个不同的枚举,不可以有相同的枚举名。(好比 enum Side{ Right, Left };enum Thing{ Wrong, Right }; 不能一起使用。)

C++11 引进了一种特别的 “枚举类”,可以避免上述的问题。使用 enum class 的语法来声明:

enum class Enumeration{ Val1, Val2, Val3 = 100, Val4 /* = 101 */,};

此种枚举为类型安全的。枚举类型不能隐式地转换为整数;也无法与整数数值做比较。 (表示式 Enumeration::Val4 == 101 会触发编译期错误)。

#include <iostream>
using namespace std;

enum class Enumeration1
{
    Val1, // 0
    Val2, // 1
    Val3 = 100,
    Val4 /* = 101 */
};

// 指定类型
enum class Enumeration2:long {val1,val2=100,val3}; // val2=100.000400 出错
int main(int argc, char** argv)
{
    Enumeration1 my=Enumeration1::Val3;
    cout<<static_cast<int>(my)<<endl;

    cout<<static_cast<double>(Enumeration2::val2)<<endl;
    return 0;
}

stringstream

int main(int argc, char *argv[]) {
  if (!glfwInit()) {
    std::cerr << "Failed to initialize GLFW." << '\n';
    return 1;
  }
  Mode mode = Mode::Standard;
  std::optional<BoundingBox> userSpecifiedBoundingBox;
  for (int i = 0; i < argc; i++) {
    const auto argument = std::string(argv[i]);
    if (argument == "--image") {
      mode = Mode::Image;
    } else if (argument == "--video") {
      mode = Mode::Video;
    } else if (argument == "--bounding-box") {
      std::stringstream values;//以下这一段没读懂
      for (int j = 0; j < 6; j++) {
        i++;
        if (j != 0) {
          values << ' ';
        }
        values << argv[i];
      }
      userSpecifiedBoundingBox = BoundingBox(values.str());
    }
  }

参考:stringstream常见用法介绍

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

cashapxxx

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值