簡體   English   中英

錯誤 C2397:從“int”到“unsigned int”的轉換需要縮小轉換

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

我在 class 中定義了一個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

如果代碼段,它指向第 2 行。

使用適當的 function 將字符串轉換為無符號 integer:

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

您可能還需要將數組定義為std::array<unsigned long, 3>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM