C++ explicit constructor/copy constructor note
C++:explict 作用显示声明构造函数只能被显示调用从而阻止编译器的隐式转换,类似只能用()显示调用,而不能=或者隐式调用
1 #include <iostream> 2 #include <vector> 3 #include <string> 4 #include <thread> 5 6 class Demo 7 { 8 private: 9 int a; 10 public: 11 explicit Demo() 12 : a(200) 13 { 14 std::cout << "默认构造函数" << std::endl; 15 } 16 17 ~Demo() 18 { 19 std::cout<<"析构函数"<<std::endl; 20 } 21 22 explicit Demo(const Demo &other) 23 { 24 a = other.a; 25 std::cout << "拷贝构造函数" << std::endl; 26 } 27 28 Demo &operator=(const Demo &other) 29 { 30 if (&other == this) 31 return *this; 32 a = other.a; 33 std::cout << "拷贝赋值构造函数" << std::endl; 34 return *this; 35 } 36 37 }; 38 39 40 void test(Demo& T) 41 { 42 43 } 44 45 46 int main() 47 { 48 Demo c; //explicit constructor; 49 Demo D(c); //explicit copy constructor 50 51 //test(D) //this is implicit,error; 52 53 return 0; 54 }