检查以下C++代码:
#include <string>
#include <map>
class A
{
public:
A (int a) {};
};
int main()
{
std::map<std::string, A> p;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
编译成功.虽然变化std::map到std::pair:
#include <string>
#include <utility>
class A
{
public:
A (int a) {};
};
int main()
{
std::pair<std::string, A> p;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
编译器会抱怨:
$ clang++ test.cpp
In file included from test.cpp:1:
In file included from /usr/bin/../lib64/gcc/x86_64-pc-linux-gnu/7.3.0/../../../../include/c++/7.3.0/string:40:
In file included from /usr/bin/../lib64/gcc/x86_64-pc-linux-gnu/7.3.0/../../../../include/c++/7.3.0/bits/char_traits.h:39:
In file included from /usr/bin/../lib64/gcc/x86_64-pc-linux-gnu/7.3.0/../../../../include/c++/7.3.0/bits/stl_algobase.h:64:
/usr/bin/../lib64/gcc/x86_64-pc-linux-gnu/7.3.0/../../../../include/c++/7.3.0/bits/stl_pair.h:219:18: error: no matching
constructor for initialization of 'A'
: first(), second() { }
^
test.cpp:13:31: note: in instantiation of member function 'std::pair<std::__cxx11::basic_string<char>, A>::pair'
requested here
std::pair<std::string, A> p;
^
test.cpp:7:5: note: candidate constructor not viable: requires single argument 'a', but no arguments were provided
A (int a) {};
^
test.cpp:4:7: note: candidate constructor (the implicit copy constructor) not viable: requires 1 argument, but 0 were
provided
class A
^
1 error generated.
Run Code Online (Sandbox Code Playgroud)
为什么C++allow类型没有默认构造函数std::map而不是std::pair?
Que*_*tin 11
std::map在构造时是空的,这意味着它不需要构造一个A刚刚.的std::pair,而另一方面,已经做到这一点,以完成其初始化.
由于两者都是类模板,因此实际上只实例化了您使用的成员函数.如果要查看预期的错误,则需要让映射尝试构造默认值A,例如:
int main()
{
std::map<std::string, A> p;
p[""];
}
Run Code Online (Sandbox Code Playgroud)