可以在for循环中使用跟踪语句吗?

Will it be possible to use trace statement in for loop?

本文关键字:跟踪 语句 for 循环      更新时间:2023-10-16

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

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

我得到以下错误,

Error 1 Error C2664:"IIteratable: ConstIterator:: ConstIterator (std:: 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,我在我的代码中做错了什么

错误是您将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