【问题标题】:function object with stdout in C++C++ 中带标准输出的函数对象
【发布时间】:2013-03-14 16:43:57
【问题描述】:

如果没有cout,程序将正确运行; 为什么? 输出缓存有问题?

#include<algorithm>
#include<iostream>
#include<vector>

using namespace std;


class fn
{
    public:
        int i;
    bool operator()(int,int)
    {
        ++i;
        cout<<"what the poodles?\n";
    }
};
int main()
{
    vector<int> temp(9,9);
    vector<int> tmp(2,3);
    fn f;
    vector<int>::iterator ite;
    ite=find_first_of(temp.begin(),temp.end(),tmp.begin(),tmp.end(),f);
    if(ite==temp.end())cout<<"Pomeranians!\n";
    //cout<<"compared "<<f.i<<" time(s)\n";//if note this ,you'll get defferent output.
    return 0;
}

【问题讨论】:

  • 代码中的脏话有什么原因吗?
  • 你有一个返回布尔值的函子,没有返回语句。
  • 你应该认为编译器警告和错误一样糟糕 :) 它们比错误更令人沮丧。

标签: c++ function-object


【解决方案1】:

三个想法:

  1. fn::operator()(int, int) 返回 bool 但没有返回语句。该函数不是正确的 C++。

  2. 当我修复那条线时,我得到了我期望的输出。如果答案的第一部分不能解决您的问题,您能否详细说明您的问题,包括您看到的输出、您期望的输出以及它们之间的差异。

  3. 您还增加了一个未初始化的变量fn::i。这对你没有任何帮助。您应该在构造函数中对其进行初始化。如果您尝试打印此变量(或以任何方式检查它),它可能有任何值,因为它的起始值可能是任何值(可能是 0,也可能是其他任何值)。


详细来说,我的编译器警告我以下问题:

foo.cc:16:3: 警告:控制到达非 void 函数的结尾 [-Wreturn-type]

为了解决这个问题,我在函子末尾添加了一个return false;,我看到了以下输出,这对我来说很有意义。

[11:47am][wlynch@watermelon /tmp] ./foo
what the poodles?
what the poodles?
what the poodles?
what the poodles?
what the poodles?
what the poodles?
what the poodles?
what the poodles?
what the poodles?
what the poodles?
what the poodles?
what the poodles?
what the poodles?
what the poodles?
what the poodles?
what the poodles?
what the poodles?
what the poodles?
Pomeranians!

【讨论】:

  • 但是,如果我在添加 return false 之前用 cout 记下语句,为什么它也能正常运行?(输出与您发布的相同).....ps 变量我只是为了计数,我在我的代码中使用了全局变量;
  • 您在添加 return false 之前编写的代码不是有效代码。您必须以 return 语句结束函数,否则整个程序无效,并且可能会出现奇怪的副作用。这些副作用可能是您所期望的,也可能不是您所期望的。另外,关于你的 cout 声明,请阅读我的第三点,如果这没有意义,请告诉我。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多