是否可以在for循环中使用trace语句?

时间:2015-09-22 05:04:15

标签: c++ loops for-loop trace comma-operator

我需要在for循环的每个语句中打印一些东西。因为我的程序在for循环中崩溃。所以我尝试在for循环中添加trace语句,

for (  ICollection::const_iterator iter = pCol->begin(NULL),OutputDebugString(L"One"); iter != pCol->end(NULL); ++iter)
        { //see OutputDebugString

我收到了以下错误,

  

错误1错误C2664:   ' IIteratable :: ConstIterator :: ConstIterator(性病:: auto_ptr的< _Ty>)'   :无法转换参数1来自' const wchar_t [4]'至   '的std :: auto_ptr的< _Ty>' filename.cpp 629

现在我在示例应用程序中尝试了同样的事情,它工作正常,

void justPrint(std::string s)
{
    cout<<"Just print";
}

int main()
{
    int i;

    for(i = 0,justPrint("a"); i<3; i++)
    {

    }

    return 0;
}

OutputDebugString和justPrint都返回void,我在代码中做错了什么。

1 个答案:

答案 0 :(得分:0)

错误是您要将OutputDebugString的返回值分配给iter。尝试交换顺序,因为逗号运算符(,)给出最后一个值,在这种情况下,是OutputDebugString的返回值。

for (  ICollection::const_iterator iter = (OutputDebugString(L"One"), pCol->begin(NULL)); iter != pCol->end(NULL); ++iter)
    { //see OutputDebugString

但是为什么你需要OutputDebugString呢?您可以在for循环之前添加它以避免混淆。

如果需要在pCol->end(NULL)之后打印调试字符串,则可以使用辅助函数。

static ICollection::const_iterator begin_helper(SomeType &pCol) {
    auto iter = pCol->begin(NULL);
    OutputDebugString(L"One")
    return iter;
}

for (  ICollection::const_iterator iter = begin_helper(pCol); iter != pCol->end(NULL); ++iter)
    { //see OutputDebugString