【问题标题】:Warning C4267 in Visual Studio: 'argument': conversion from 'size_t' to 'const _Elem', possible loss of dataVisual Studio 中的警告 C4267:“参数”:从“size_t”转换为“const _Elem”,可能丢失数据
【发布时间】:2021-01-06 03:08:13
【问题描述】:

我从这个函数中得到警告:

std::pair<size_t, size_t> GetSection(const string& s1, const string& s2) {
        size_t top_section = s1.find(s2 + ":");
        size_t bottom_section = s1.find(s1.length() - top_section);

        return std::make_pair(top_section, bottom_section);
}

我不明白是什么转换导致了问题。 我也明白这个函数可以这样写:

    std::pair<size_t, size_t> GetSection(const string& s1, const string& s2) {
        size_t top_section = s1.find(s2 + ":");
        size_t bottom_section = top_section + s2.length() + 1;

        return std::make_pair(top_section, bottom_section);
}

我只是想知道为什么会收到此警告。

【问题讨论】:

  • s1.find(s1.length() - top_section); find 应该是什么?

标签: c++


【解决方案1】:

问题出在这个函数调用中:

s1.find(s1.length() - top_section);

参数s1.length() - top_section 是一个size_t 类型的数字,但find 方法应该接受一个字符串字符 进行搜索。

(具体来说,因为 C++ 总是假设你的意思是你所说的,它试图将 size_t 转换为 char,但这会导致精度损失,因为 char 类型只有 8 位宽。)

【讨论】:

    猜你喜欢
    • 2018-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多