【问题标题】:conversion from 'unsigned int' to 'int' requires a narrowing conversion从“unsigned int”到“int”的转换需要缩小转换
【发布时间】:2021-01-02 20:53:40
【问题描述】:

我的代码包括以下内容,我根据下面的最后一行收到上面的错误消息。

struct List {
    int word_i;
    int mod_i;
    char mod_type;
    char mod_char;
};

struct Morph {
    Options mode;
    deque<List> search_list;
    vector<string> dictionary;
    vector<bool> discovered;
    string output;
    int sel_word_i = 0;
    bool end_found = 0;
};

// later on in a function:
morph->search_list.push_back({ morph->dictionary.size() - 1, 0, 0, 0 });

【问题讨论】:

  • morph-&gt;dictionary.size() 返回一个未签名的size_t。为了以这种方式使用它,您需要转换为 int
  • size()返回0时,0 - 1是什么?
  • 您想知道为什么编译器会报告这种警告吗?您是否关心如何删除警告?

标签: c++ compiler-errors type-conversion integer unsigned


【解决方案1】:

您可以将最后一行替换为:

morph->search_list.emplace_back( morph->dictionary.size() - 1, 0, 0, 0 );

因此对象不是通过大括号初始化创建的,它不允许缩小转换。

缩小转换是从调用的返回值到size,它返回无符号的std::size_t

关于为什么size() - 1 不转换为有符号值,请参阅:C++ Implicit Conversion (Signed + Unsigned)

【讨论】:

  • 这样就解决了这个错误,但现在我得到以下信息:术语不计算为采用 1 个参数的函数
  • @FranciscoSkrobola - 仔细阅读。您需要将被调用的成员函数从push_back() 更改为emplace_back()。当您尝试构造和添加对象时,两者不可互换。
  • 我确实更改了它,但这样做导致了评估错误
猜你喜欢
  • 1970-01-01
  • 2020-06-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-05
  • 2013-09-03
  • 2012-04-28
相关资源
最近更新 更多