为什么不能为类型的函数参数设置默认值<map>?

Why can't I set a default value for a function parameter of <map> type?

本文关键字:lt map gt 默认值 设置 不能 类型 参数 函数 为什么      更新时间:2023-10-16

下面是我的示例程序,它不会编译。我想创建一个函数,该函数将映射作为可能的参数,但如果没有提供映射,则提供默认的空映射。很直接,只是不确定为什么它不起作用。

#include <map>
#include <iostream>
using std::cout; using std::endl; using std::map;
int func(map<int, int>& = map<int, int>());
int main() {
    map<int, int> m;
    m[2] = 4;
    cout << "func() = " << func() << endl;   // "func() = 0"
    cout << "func(m) = " << func(m) << endl; // "func(m) = 1"
}
int func(map<int, int>& m) { return m.size(); }

我得到的编译器错误是:

test.cc:6:42: error: default argument for 'std::map<int, int>& <anonymous>' has type 'std::map<int, int>'

请解释一下,这对我来说没有意义。

您可以使用常量引用绑定临时对象。因此,该函数可能被声明为

int func( const map<int, int>& = map<int, int>());