C++对象的构造(上)

--事物的难度远远低于对事物的恐惧!

    在开始对象的构造知识点讲解之前,我们先来思考个小问题:生成一个类对象时,其中的成员变量的初始值是多少?要理解上边的问题,我们首先要有一个概念:定义类对象可视为定义变量,根据我们C语言的基础,在全局区、栈空间、堆空间定义的变量,初始值都有所不同,其中全局区初始值为0,栈空间上为随机值,堆空间上为随机值。

那么我们以下边的代码来验证一下我们的猜想:

#include <iostream>

using namespace std;

class testClass
{
private:
	int i;
	int j;

public:
	int getI()
	{
		return i;
	}
	int getJ()
	{
		return j;
	}
};

testClass t1;	//全局区上定义类对象

int main()
{ 	
	testClass t2; //栈空间上定义类对象

	testClass *t3 = new testClass; //堆空间上定义类对象

	cout << "t1.getI() = " << t1.getI() << endl;
	cout << "t1.getJ() = " << t1.getJ() << endl << endl;
	
	cout << "t2.getI() = " << t2.getI() << endl;
	cout << "t2.getJ() = " << t2.getJ() << endl << endl;
	
	cout << "t3->getI() = " << t3->getI() << endl;
	cout << "t3->getJ() = " << t3->getJ() << endl;

	delete t3;

	system("pause");
	return 0;
}

编译输出如下:

从输出我们可以看到,跟我们设想的一样,定义对象与定义变量一样。
    -上定义的对象,成员变量初始值为随机值
    -上定义的对象,成员变量的初始值为随机值
    -局区定义的对象,成员变量的初始值为0

因为初始值得不确定,那么如果想要初始化一个对象,改怎么解决?
    -为每个类增加一个初始化成员函数init(),在对象定义后显示调用该函数(缺点是需要立即显示调用,隐患较大)
    -使用C++中的构造函数
由于第一种方式弊端较多,我们重点来分析第二种方式;首先来看下C++中的构造函数的概念
    -C++中构造函数:是一种特殊的成员函数, 函数名与类名相同无返回值,类对象创建时自动调用
所以上边代码中的testClass类的构造函数为:testClass(),重新更新代码如下:
 

#include <iostream>

using namespace std;

class testClass
{
private:
	int i;
	int j;

public:

	testClass()    //构造函数,对象创建时自动调用
	{
	    cout << "testClass() called" << endl;
		i = 1;
		j = 2;
	}

	int getI()
	{
		return i;
	}
	int getJ()
	{
		return j;
	}
};

testClass t1;	//全局区上定义类对象

int main()
{ 	
	testClass t2; //栈空间上定义类对象

	testClass *t3 = new testClass; //堆空间上定义类对象

	cout << "t1.getI() = " << t1.getI() << endl;
	cout << "t1.getJ() = " << t1.getJ() << endl << endl;
	
	cout << "t2.getI() = " << t2.getI() << endl;
	cout << "t2.getJ() = " << t2.getJ() << endl << endl;
	
	cout << "t3->getI() = " << t3->getI() << endl;
	cout << "t3->getJ() = " << t3->getJ() << endl;

	delete t3;

	system("pause");
	return 0;
}

编译输出如下:

由输出可以看到,我们定义了三个对象,构造函数被调用的3次,也就是说在定义对象时就自动调用构造函数去初始对象

总结:
    -C++中可以通过构造函数完成对象的初始化
    -C++中的构造函数是一种特殊的成员函数, 函数名与类名相同无返回值,类对象创建时自动调用

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值