【发布时间】:2021-11-10 11:41:08
【问题描述】:
class A {
int x;
std::string s;
public:
A(std::string _s): x(0), s(_s) {
std::cout << "\tA(string)\n" ;
}
A(int _x): x(_x), s("") {
std::cout << "\tA(int)\n" ;
}
A(const A &other): x(other.x), s(other.s) {
std::cout << "\tA(A& other)\n" ;
}
};
int main() {
std::string str = "Hello";
A obj_1(str);
A obj_2 = str;
A obj_3(10);
A obj_4 = 10;
char ch = 'a';
A obj_5 = ch; // How is this working?
// A obj_6 = "Hello"; // And not this?
const char *ptr = "Hello";
// A obj_7 = ptr; // or this?
return 0;
}
执行此代码时,输出为:
A(string)
A(string)
A(int)
A(int)
A(int)
据我了解,obj_1 和 obj_3 是使用各自的 ctor 直接创建的。对于obj_2 和obj_4,编译器通过调用它们各自的ctor 进行隐式转换(因此在每种情况下只需要1 次隐式转换)。但是,对于obj_5,编译器首先必须将 char 转换为 int,然后再进行一次隐式转换以调用 int-ctor。但是 C++ 标准只允许 1 次隐式转换。那么这里发生了什么?
此外,在这种情况下,"Hello" 应首先转换为 std::string,然后再进行一次隐式转换以调用 string-ctor。但这不起作用。
【问题讨论】:
标签: c++ constructor c++17 implicit-conversion