在 C++11 中定义 lambda 函数不会在内部编译 class

Defining a lambda function in C++11 doesn't compile inside class

我试图在 C++ class 中创建一个 lambda 函数,但它给出了编译错误。代码如下:

class Test {

  public:
    struct V {
            int a;
    };

    priority_queue<V, vector<V>, function<bool(V&, V&)>>
            max_heap([](V& a, V& b) { return true; } );

};

我得到的编译错误是:

test.cpp:32:22: error: expected identifier before '[' token
             max_heap([](V& a, V& b) { return true; } );
                      ^
test.cpp:32:35: error: creating array of functions
             max_heap([](V& a, V& b) { return true; } );
                                   ^
test.cpp:32:37: error: expected ')' before '{' token
             max_heap([](V& a, V& b) { return true; } );
                                     ^
test.cpp:32:54: error: expected unqualified-id before ')' token
             max_heap([](V& a, V& b) { return true; } );

有什么解释吗?

您不能在 class 正文中使用 () 构造 class 成员。编译器将此解释为试图创建一个函数。由于你有 C++11,你可以使用大括号初始化来克服这个问题,比如

class Test {

  public:
    struct V {
            int a;
    };

    std::priority_queue<V, vector<V>, function<bool(V&, V&)>>
            max_heap{[](V& a, V& b) { return true; } };

};