原创 linux下c++ lesson6 动态对象创建

28 篇文章 0 订阅

1-malloc.cpp

#include <iostream>
#include <stdlib.h>

using namespace std;

class Test
{
public:
	Test()
	{
		cout  << "Test构造函数" << endl;
	}
	~Test()
	{
		cout << "Test析构函数" << endl;
	}
};

int main()
{
	//Test t1;    //栈空间创建对象

	//创建对象 1、申请空间  2、调用构造函数初始化    C++中不用malloc创建对象
	Test *pt = (Test *)malloc(sizeof(Test) * 1);   //在堆空间申请一个对象大小的内存
	if (NULL == pt)
	{
		cout << "malloc failure" << endl;
	}

	free(pt);   //释放内存,不是释放对象

	Test *pt2 = new Test;    //1、申请内存(堆)  2、调用构造函数  自动调用构造函数
	delete pt2;              //调用析构函数

	return 0;
}

2-new.cpp

#include <iostream>

using namespace std;

class Test
{
public:
	Test()
	{	
		cout << "无参构造函数" << endl;
	}
	Test(int a, int b)
	{
		cout << "有参构造函数" << endl;
	}
	~Test()
	{
		cout << "析构函数" << endl;
	}
};

int main()
{
	int *p1 = new int;     //给一个整数申请空间
	cout << *p1 << endl;
	delete p1;

	char *p2 = new char;   //给一个字符申请空间
	delete p2;

	int *p3 = new int(100);  //给一个整数申请空间同时初始化为100
	cout << *p3 << endl;
	delete p3;

	char *p4 = new char[10];   //给十个字符申请空间
	delete[] p4;

	Test *t1 = new Test;
	delete t1;

	Test *t2 = new Test(1, 2);
	delete t2;

	return 0;
}

3-对象初始化列表.cpp

#include <iostream>

using namespace std;

class Date
{
private:
	int year;
	int mouth;
	int day;
public:
	/*Date()
	{
		year = 1999;
		mouth = 1;
		day = 1;
	}*/
	Date(int y, int m, int d)
	{
		year = y;
		mouth = m;
		day = d;
	}
};


//对象初始化列表:1、类对象作为成员变量并且该类没有提供无参构造函数  2、成员变量被const修饰(初始化和赋值不同)
class Student
{
private:
	const int id;
	Date birth;
public:
	Student(int i, int y, int m, int d) : birth(y, m, d), id(i)
	{	

	}
};

int main()
{
	Student s1(1, 1999, 2, 2);

	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值