排序功能不适用于在堆栈上创建的功能对象? [英] Sort function does not work with function object created on stack?

查看:73
本文介绍了排序功能不适用于在堆栈上创建的功能对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include<iostream>
#include<vector>
#include<algorithm>
class Integer
    {
public:
    int m;
    Integer(int a):m(a){};
    };
class CompareParts
    {
    public:
        bool operator()(const Integer & p1,const Integer & p2)
            {
            return p1.m<p2.m;
            }
    }obj1;
int main()
    {
    std::vector<Integer> vecInteger;
    vecInteger.push_back(Integer(12));
    vecInteger.push_back(Integer(13));
    vecInteger.push_back(Integer(5));
    vecInteger.push_back(Integer(7));
    vecInteger.push_back(Integer(9));
    Integer obj2();
    std::sort(vecInteger.begin(),vecInteger.end(),obj1);
    std::sort(vecInteger.begin(),vecInteger.end(),obj2);
    }

为什么obj2在第二排序函数中会导致编译器错误.

why is obj2 in second sort function leads to compiler error.

推荐答案

Integer obj2()不是对象的定义,它是名为obj2的函数的声明,该函数返回Integer(将其放置在任何函数来了解为什么会这样).有时在更复杂的结构中也会发生这种情况,这可能会更加令人困惑.有人将其命名为最令人烦恼的解析.

Integer obj2() isn't the definition of an object, it is the declaration of a function named obj2 returning an Integer (put it outside any function to understand why it is so). This occurs also sometimes with more complex constructions where it can be even more confusing. Some name this the most vexing parse.

这是一个更为复杂的案例的应有的例子:

Here is the promised example of a more complex case:

struct Foo {};
struct Bar { Bar(Foo); };

Bar quxx(Foo()); // quxx is a function

此处quxx是一个返回Bar并将(指针)带到返回Foo且不带参数的函数的函数.您可以像这样更清楚地写相同的声明:

Here quxx is a function returning a Bar and taking (a pointer) to a function returning a Foo and without parameters. You could write the same declaration more clearly like this:

Bar quxx(Foo (*fn)()); // quxx is the same function as above

要获取使用构造函数接受Foo初始化的变量的定义,可以添加括号级别:

To get the definition of a variable initialized with the constructor taking a Foo, you can add a level of parenthesis:

Bar quux((Foo())); // quux is a variable

这篇关于排序功能不适用于在堆栈上创建的功能对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆