以下代码编译失败
#include <iostream>
#include <map>
#include <vector>
using namespace std;
class mc
{
string s;
public:
mc(const std::string s) : s{s}{};
// mc(const char * s) : s{s}{}; // Adding this line would make it work in both cases
};
int main()
{
vector<mc> a = {"Hello", "there"}; //FAILS
vector<mc> b = {mc("Hello"), mc("there")}; //WORKS
}
取决于编译器错误是
no matching function for call to mc::mc(const char&)
note: candidate: ‘mc::mc(std::string)’
note: no known conversion for argument 1 from ‘const char’ to ‘std::string’
或
/usr/include/c++/11/bits/stl_uninitialized.h:138:72: error: static assertion failed: result type must be constructible from value type of input range
为什么会出现这个错误? 有一个来自字符串的隐式构造函数。 如果不是
vector<mc>
他们是vector<string>
它会起作用。