C++也可以和Java一样不显示声明类的构造函数,编译器在创建对象时调用默认的构造函数。但C++的成员变量的初始值是不确定的,尤其是int类型的变量,初始值未知,容易导致不确定的bug,给程序运行带来麻烦。所以在声明类时还是声明默认的构造函数并初始化变量,养成好的编码风格。
下面是声明类时没有显示声明构造函数和显示声明了构造函数的简单实例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60#include "stdafx.h" #include <string> #include <iostream> using namespace std; // 没有显示声明构造函数,编译器会调用默认的构造函数 class Test1 { public: int i; string str; }; // 显示声明了构造函数 class Test2 { public: Test2(); Test2(int i, string s); int i; string str; }; Test2::Test2():i(0), str("Test2") { cout<<"Test2()"<<endl; } Test2::Test2(int i, string s):i(i), str(s) { cout<<"Test2(int i, string s)"<<endl; } int _tmain(int argc, _TCHAR* argv[]) { cout<<"----------------调用默认构造函数,成员变量初始值不确定----------------"<<endl; Test1 *t = new Test1; cout<<"t->i = "<<t->i<<", t->str = ["<<t->str<<"]"<<endl; printf("t->i = %d, t->str = [%s]n", t->i, (const char *)t->str.c_str()); cout<<endl<<"----------------调用默认构造函数,并为其成员变量设置初始值----------------"<<endl; Test1 *t1 = new Test1; t1->i = 0; t1->str = "Test1"; cout<<"t1->i = "<<t1->i<<", t1->str = ["<<t1->str<<"]"<<endl; printf("t1->i = %d, t1->str = [%s]n", t1->i, (const char *)t1->str.c_str()); cout<<endl<<"----------------调用自定义的无参构造函数,在构造函数中进行初始化成员变量----------------"<<endl; Test2 *t2 = new Test2; cout<<"t2->i = "<<t2->i<<", t2->str = ["<<t2->str<<"]"<<endl; printf("t2->i = %d, t2->str = [%s]n", t2->i, (const char *)t2->str.c_str()); cout<<endl<<"----------------调用自定义的有参构造函数,在构造函数中进行初始化成员变量----------------"<<endl; Test2 *t3 = new Test2(100, "Today is very hot!"); cout<<"t3->i = "<<t3->i<<", t3->str = ["<<t3->str<<"]"<<endl; printf("t3->i = %d, t3->str = [%s]n", t3->i, (const char *)t3->str.c_str()); int x; cin>>x; return 0; }
在VS2012上运行结果如下:
----------------调用默认构造函数,成员变量初始值不确定----------------
t->i = -842150451, t->str = []
t->i = -842150451, t->str = []
----------------调用默认构造函数,并为其成员变量设置初始值----------------
t1->i = 0, t1->str = [Test1]
t1->i = 0, t1->str = [Test1]
----------------调用自定义的无参构造函数,在构造函数中进行初始化成员变量----------------
Test2()
t2->i = 0, t2->str = [Test2]
t2->i = 0, t2->str = [Test2]
----------------调用自定义的有参构造函数,在构造函数中进行初始化成员变量----------------
Test2(int i, string s)
t3->i = 100, t3->str = [Today is very hot!]
t3->i = 100, t3->str = [Today is very hot!]
最后
以上就是和谐服饰最近收集整理的关于C++类可以不显示声明构造函数,在创建类对象时编译器自动调用默认的构造函数...的全部内容,更多相关C++类可以不显示声明构造函数,在创建类对象时编译器自动调用默认内容请搜索靠谱客的其他文章。
发表评论 取消回复