#include <iostream>
#include <string>
class testClass {
public:
// testClass(const char * s)
// {
// std::cout<<"custom constructor 1 called"<<std::endl;
// }
testClass(std::string s) : str(s)
{
std::cout<<"custom constructor 2 called"<<std::endl;
}
private:
std::string str;
};
int main(int argc, char ** argv)
{
testClass t0{"str"};
testClass t2 = {"string"};
testClass t4 = "string"; // error conversion from 'const char [7]' to non-scalar type 'testClass' requested
return 0;
}
似乎复制初始化不允许隐式转换const char *
,string
而复制列表初始化和直接初始化允许它。