gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 23:38:27 25 4
gpt4 key购买 nike

这段代码在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com