【问题标题】:error C2397: conversion from 'int' to 'unsigned int' requires a narrowing conversion错误 C2397:从“int”到“unsigned int”的转换需要缩小转换
【发布时间】:2020-04-13 11:21:56
【问题描述】:

我在一个类中定义了一个std::array<unsigned, 3>。我想在构造函数中初始化它,如下所示:

MyClass::MyClass(std::map<std::string, std::string> const&data)
{
MyArr[0] = (unsigned)(std::atoi(data["one"].c_str()));
MyArr[1] = (unsigned)(std::atoi(data["two"].c_str()));
MyArr[2] = (unsigned)(std::atoi(data["three"].c_str()));
}

通过在最新的 MSVC 版本中编译此代码

cl /EHsc /O2 /std:c++17 main.cpp

我明白了

error C2397: conversion from 'int' to 'unsigned int' requires a narrowing conversion

如果sn-p,它指向第2行。

【问题讨论】:

  • 仅供参考,sn-p 的第 2 行是一个开括号。你的意思是分配给MyArr[0],是(否)?
  • 无法在 const 对象上调用 operator[],您的地图被标记为 const。也使用 std::stoul 代替 atoi。
  • Why shouldn't I use atoi()?。使用std::stoul 代替它直接接收std::string 并且您不需要.c_str(0)How can I convert a std::string to int?
  • 谢谢大家。 std::stoul 帮了我大忙。

标签: c++ visual-c++ c++17 type-narrowing


【解决方案1】:

使用适当的函数将字符串转换为无符号整数:

char* end;
MyArr[0] = std::strtoul(data["one"].c_str(), &end, 10);

您可能还需要将您的数组定义为std::array&lt;unsigned long, 3&gt;

【讨论】:

猜你喜欢
  • 2021-01-02
  • 1970-01-01
  • 2020-06-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-07
  • 2014-04-05
相关资源
最近更新 更多