c – 取消引用字符串迭代器产生int

前端之家收集整理的这篇文章主要介绍了c – 取消引用字符串迭代器产生int前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我收到这个错误
comparison between pointer and integer ('int' and 'const char *')

对于以下代码

#include <iostream>
#include <sstream>
#include <string>

using namespace std;

int main()
{
    std::string s("test string");
    for(auto i = s.begin(); i != s.end(); ++i)
    {
        cout << ((*i) != "s") << endl;
    }
}

为什么解除引用字符串迭代器会产生一个int而不是std :: string?

解决方法

实际上,它不会产生一个int,它会产生一个char(因为字符串迭代器迭代字符串中的字符).由于!=的另一个操作数不是char(它是一个const char [2]),标准的促销和转换将应用于参数:

>通过整体推广将char提升为int
> const char [2]通过数组到指针的转换转换为const char *,

这是你到达编译器抱怨的int和const char *操作数的方法.

您应该将解除引用的迭代器与字符进行比较,而不是与字符串进行比较:

cout << ((*i) != 's') << endl;

“”包含一个字符串文字(类型const char [N]),”包含一个字符文字(char类型).

原文链接:https://www.f2er.com/c/111076.html

猜你在找的C&C++相关文章