C++类可以不显示声明构造函数,在创建类对象时编译器自动调用默认的构造函数

C++也可以和Java一样不显示声明类的构造函数,编译器在创建对象时调用默认的构造函数。但C++的成员变量的初始值是不确定的,尤其是int类型的变量,初始值未知,容易导致不确定的bug,给程序运行带来麻烦。所以在声明类时还是声明默认的构造函数并初始化变量,养成好的编码风格。

下面是声明类时没有显示声明构造函数和显示声明了构造函数的简单实例:

#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!]


©️2020 CSDN 皮肤主题: 大白 设计师: CSDN官方博客 返回首页
实付0元
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值