声明一个对象,不加括号一般调用默认构造函数
15 T t1; // is obj:Default Constructor
注意:如声明一个对象,加括号,这里一般编译器把这个当成无形参的函数,返回类型为T
18 T t2(); // is function. name is t2, return T声明一个对象,加括号一般调用用户定义的构造函数
21 T t3(3); // is obj. Define Constructor
new关键字创建对象时
对于内置类型(比如int, char):加括号会初始化,不加括号不初始化.对于自定义类型:都会调用默认构造函数,加不加括号没区别.
1 #include2 #include 3 #include 4 5 class T { 6 public: 7 T(){printf("Default Constructor!\n");}; 8 T(int a){printf("Define(%d) Constructor!\n", a);}; 9 10 ~T(){printf("Destructor!\n");};11 };12 13 int main(int argc, char *argv[])14 {15 T t1; // is obj:Default Constructor16 printf("______1st_______\n");17 18 T t2(); // is function. name is t2, return T19 printf("______2nd_______\n");20 21 T t3(3); // is obj. Define Constructor22 printf("______3th_______\n");23 24 T* t4 = new T; // is Point. DC25 printf("______4th_______\n");26 27 T* t5 = new T(); // is Point. DC28 printf("______5th_______\n");29 30 delete t4;31 delete t5;32 33 return (EXIT_SUCCESS);34 }
输出
root@ubuntu:~/Test/test/
$ a.outDefault Constructor!
______1st_____________2nd_______Define(3) Constructor!______3th_______Default Constructor!______4th_______Default Constructor!______5th_______Destructor!Destructor!Destructor!Destructor!