c++ - C++ 中带标准输出的函数对象

标签 c++ function-object

如果没有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;
}

最佳答案

三个想法:

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

  2. 当我修复该行时,我得到了我期望的输出。如果答案的第一部分没有解决您的问题,您能否在您的问题中详细说明您看到的输出和您期望的输出,并说明它们的不同之处。

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


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

foo.cc:16:3: warning: control reaches end of non-void function [-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!

关于c++ - C++ 中带标准输出的函数对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15415236/

相关文章:

c++ - 如何在类中使用 char*

c++ - 聚合初始化不支持构造函数访问

c++ - 我可以在不实例化的情况下使用函数对象吗?

c++ - 如何将 std::function 分配给 C++ 中的运算符?

c++ - 错误 : expected unqualified-id while using boost mutex

c++ - stringstream 重复最后一个词

c++ - 从 vector 的 std::tuple 中迭代选定的 vector

c++ - 重载运算符 ()

c++ - 函数对象作为模板参数

c++ - 在哪里定义谓词和函数对象?