【问题标题】:Will it be possible to use trace statement in for loop?是否可以在 for 循环中使用跟踪语句?
【发布时间】:2015-12-18 22:50:23
【问题描述】:

我需要在 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(std::auto_ptr<_ty>)' : 无法将参数 1 从 'const wchar_t [4]' 转换为 'std::auto_ptr<_ty>' 文件名.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,我在代码中做错了什么。

【问题讨论】:

  • pCol的类型是什么?还有为什么在begin() 和end() 中使用NULL?
  • std::auto_ptr...一些遗留代码需要升级...
  • pCol 是某种内部类型的智能指针,TNSmartPtr&lt;IEbCollection&gt; pCol 并传递了 NULL,因为它需要一些会话对象。都与内部管理有关。是否应该出现任何错误?因为没有跟踪语句一切都很好。
  • @BryanChen 是的。但它巨大的旧遗留代码。我正在修复小模块上的错误。如果尝试这样做,需要大量重构。
  • 在 for 循环的第一个参数中包含 print 语句有什么意义?由于无论如何它只会执行一次,为了清楚起见,您不妨将其移出循环。

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


【解决方案1】:

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

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

但这就是你需要OutputDebugString 的原因吗?您可以在 for 循环之前添加它以避免混淆。


如果您需要在pCol-&gt;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

【讨论】:

  • 我想看看在赋值和 for 循环的其他部分之后会发生什么,因为我在 for 循环中遇到错误。我的意思不是循环语句,而是循环本身的定义。
  • 我的错误已解决。谢谢。一个问题,为什么编译器不认为我在这里将 justPrint 分配给 i,for(i = 0,justPrint("a"); i&lt;3; i++)
  • @PranitKothari 赋值的优先级高于逗号运算符,因此相当于((i = 0), justPrint("a"))。 int i = 0, justPrint("a") 失败,因为它是初始化;相当于int i = (0,justPrint("a"))
猜你喜欢
  • 1970-01-01
  • 2023-02-07
  • 2018-08-10
  • 2020-03-26
  • 2014-04-25
  • 2019-03-15
  • 2018-03-11
  • 2017-05-12
  • 1970-01-01
相关资源
最近更新 更多