简体   繁体   中英

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

I have an std::array<unsigned, 3> defined inside a class. I want to initalise it inside the constructor, like this:

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()));
}

By compiling this code in the latest MSVC release with

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

I get

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

it points to the line 2 if the snippet.

Use the appropriate function to convert string to an unsigned integer:

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

You might also need to define your array as std::array<unsigned long, 3> .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM