c++ - 将 C++ 代码从 VC6 迁移到 VS2008 后出现错误 C2678 - 未找到采用 'type' 类型左侧操作数的运算符

标签 c++ visual-studio visual-studio-2008 visual-c++-6

这段代码在 VC6 中编译文件,但在 VS 2008 中却报错。谁能告诉我为什么? 我想这是因为您不能再将指针与 NULL 进行比较(这是 0 的 typedef)。 如果是这样,我如何在 VC9 中进行这种比较?

for ( std::vector<aCattrBase*>::iterator iT = attrLst.begin(); iT < attrLst.end(); iT++)
        { 
            if ( (iT != NULL) && (*iT != NULL) ) //Error: C2678
            {
//code
}
}

error C2678: binary '!=' : no operator found which takes a left-hand operand of type 'std::_Vector_iterator<_Ty,_Alloc>' (or there is no acceptable conversion)

最佳答案

'std::vector::iterator' 的类型不一定是指针类型,因此您不能将它与 NULL 进行比较。

在您的旧编译器中,它恰好是一个指针,因此您的代码已编译。但是您很幸运(如将代码移至其他编译器时所示)。

您对迭代器的唯一测试是将它与 end() 或 begin() 或 begin() -> end() 范围内的任何有效迭代器进行比较。由于这是一个 vector ,您可以使用迭代器进行数学运算。 iT-begin() 应该给你一个偏移量。但这并非对所有容器都有效(检查每个容器文档)。

您需要做的就是测试迭代器指向的内容:

for ( std::vector<aCattrBase*>::iterator iT = attrLst.begin();
      iT != attrLst.end();  // Changed this. Notice the !=
      ++iT)                 // Changed this. Prefer pre increment for not integer types
{ 
    if ( *iT != NULL)
    {
         //code
    }
}

关于c++ - 将 C++ 代码从 VC6 迁移到 VS2008 后出现错误 C2678 - 未找到采用 'type' 类型左侧操作数的运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/968602/

相关文章:

c# - 办公室 2007 : Programmatically control Out-Of-Office assistant?

c++ - 无法在 OpenCV 中创建/保存输出 avi 文件

c++ - 每次复制实现移动赋值的非 const 对象时,我是否总是获得移动语义?

c++ - 'char*'的模板参数推导

c++ - C++中 vector 的 vector 的顺序是什么

visual-studio - 在 Visual Studio 2008 中在拆分窗口之间跳转的热键是什么

c# - 如何为 Visual Studio 使用的 IIS Express 添加 net.tcp 协议(protocol)支持?

asp.net - Visual Studio Publish 停留在为路径添加 ACL

c++ - WinAPI 中的 Windows 10 用户界面

c - visual studio 2008 目标机器类型列表