类对象加括号与不加括号
程序员文章站
2023-04-08 10:11:59
声明一个对象,不加括号一般调用默认构造函数 15 T t1; // is obj:Default Constructor 注意:如声明一个对象,加括号,这里一般编译器把这个当成无形参的函数,返回类型为T18 T t2(); // is function. name is t2, return T 声 ......
声明一个对象,不加括号一般调用默认构造函数
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 #include <stdio.h> 2 #include <stdlib.h> 3 #include <unistd.h> 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 Constructor 16 printf("______1st_______\n"); 17 18 T t2(); // is function. name is t2, return T 19 printf("______2nd_______\n"); 20 21 T t3(3); // is obj. Define Constructor 22 printf("______3th_______\n"); 23 24 T* t4 = new T; // is Point. DC 25 printf("______4th_______\n"); 26 27 T* t5 = new T(); // is Point. DC 28 printf("______5th_______\n"); 29 30 delete t4; 31 delete t5; 32 33 return (EXIT_SUCCESS); 34 }
输出
root@ubuntu:~/Test/test/
$ a.out
Default Constructor!
______1st_______
______2nd_______
Define(3) Constructor!
______3th_______
Default Constructor!
______4th_______
Default Constructor!
______5th_______
Destructor!
Destructor!
Destructor!
Destructor!