代码之家  ›  专栏  ›  技术社区  ›  bobbyalex

将C++代码从VC6迁移到VS2008后出现错误C2678-找不到接受“type”类型左手操作数的运算符

  •  2
  • bobbyalex  · 技术社区  · 17 年前

    如果是这样的话,我该如何在VC9中进行比较?

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

    类型

    4 回复  |  直到 17 年前
        1
  •  8
  •   David Rodríguez - dribeas    17 年前

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

    在你的旧编译器中,它只是一个指针,所以你的代码被编译了。但你很幸运(正如你将代码移动到另一个编译器时所示)。

    你需要做的就是测试迭代器指向什么:

    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
        }
    }
    
        2
  •  2
  •   ralphtheninja    17 年前

    迭代器不是指针,它是一个类实例,没有二进制运算符!=将其与null进行比较。

        3
  •  1
  •   Dominik Grabiec    17 年前

    您正试图在if语句的第一个条件中将迭代器与NULL进行比较。您不需要进行第一次比较,因为迭代器iT应该位于列表的有效部分内。

        4
  •  0
  •   Sliq    17 年前

    在您给出的示例中,比较是没有意义的,因为迭代器总是指向某物。正在检查(*IT)!=NULL是合理的,并且仍然有效。

    IT._Has_container()
    

    IT = std::vector<aCattrBase*>::iterator();