【发布时间】: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