为什么使用字符串文字的隐式字符串构造函数初始化类的向量会失败? [重复]

问题描述 投票:0回答:0

以下代码编译失败

#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>
它会起作用。

c++ stl c++17 implicit-conversion list-initialization
© www.soinside.com 2019 - 2024. All rights reserved.