#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
в то время как копия-инициализация списка и прямая инициализация позволяют это.
Конструктор, который ищет компилятор:
testClass(const char* s) : str(s)
{
std::cout << "custom constructor 3 called" << std::endl;
}
Я думаю, что ваш код дает сбой, потому что для этого потребуются два неявных преобразования, присваивание и const char*
в const std::string&
,
Кроме того, вы должны использовать const std::string&
вместо.
testClass(const std::string &s) : str(s)
{
std::cout<<"custom constructor 2 called"<<std::endl;
}
Потому что в testClass t4 = "string";
вы даете const char*
,
Других решений пока нет …