在向构造函数传递指针时,调用哪个构造函数(或隐式转换)

  • 本文关键字:构造函数 转换 调用 指针 c++
  • 更新时间 :
  • 英文 :

class Test {
public:

Test() {
std::cout << "constructing" << std::endl;
}
Test(Test &t) {
std::cout << "calling copy constructor" << std::endl;
}
Test(Test &&t) {
std::cout << "calling move constructor" << std::endl;
}
Test& operator=(const Test& a){
std::cout << "calling = constructor" << std::endl;
return *this;
}
};
Test* t1 = new Test(); 
Test* t2 (t1); // what's being called here 

当向t2这样的构造函数传递指针时,调用什么构造函数?(或者隐式转换,然后是构造函数?(;构造";作为构造t1的结果。

Test* t2 (t1);

是直接初始化。直接初始化考虑类类型的构造函数,但Test*是指针类型,而不是类类型。非类类型没有构造函数。

对于指针类型,在带括号的初始值设定项中使用单个表达式进行直接初始化,只需将表达式的值复制到新的指针对象中(可能是在隐式转换之后,这里不需要隐式转换(。

因此,t2将具有与t1相同的值,指向使用new Test();创建的对象。

最新更新