4种c++对象的声明及销毁方法

新开博客,没什么好写的,先放一篇以前整理的东西上来。

零:直接声明一个对象就不讲了

一:指针对象

<span style="white-space:pre">	</span>Book *aBook = nullptr;

	aBook = new Book("C++", "Gaddis", 400);

	cout<<aBook->toString()<<endl;

	delete aBook;

二:指针指向一个储存Book类对象的数组,该数组在Stack中,三个对象在Heap中,数组中储存三个对象

Book *books = nullptr;
	int capacity = 3;
	int nrOfBooks = 0;

	books = new Book[capacity];
	books[nrOfBooks++] = Book("C++", "Gaddis", 400);//后加
	books[nrOfBooks].setTitle("Java");
	books[nrOfBooks].setAuthor("Sawitch");
	books[nrOfBooks].setPrice(500);
	nrOfBooks++;

	for (int i=0; i<capacity; i++)
	{
		cout<<books[i].toString()<<endl;
	}
	system("pause");
delete [] books; //compare delete and delete[],the delete just delete books[0],but delete []can delete all objects

三.声明数组储存3个指针对象,数组在Stack中,对象在Heap

(与二的区别在于,三中的对象为指针对像,二中声明的是三个对象,而三中声明的是3个指针)

const int CAPACITY = 3;
Book *books[CAPACITY] = {nullptr, nullptr, nullptr};
books[2] = new Book("C++", "Gaddis", 400);
books[0] = new Book("Java", "Sawitch", 500);
for (int i=0; i<CAPACITY; i++)
{
if (books[i] != nullptr)
		{
			cout<<books[i]->toString()<<endl;
		}
	}

	for (int i=0; i<CAPACITY; i++)
	{
		if (books[i] != nullptr)
		{
			delete books[i];
		}
	}

四.声明一个双指针的数组对象,声明的数组在heap中,对象也在heap

Book **books = nullptr;
	int capacity = 3;
	int nrOFBooks = 0;
	string title;
	string author;
	int price;

	books = new Book*[capacity];

	for (int i=0; i<capacity; i++)
	{
		books[i] = nullptr;
	}

	books[nrOFBooks++] = new Book("C++", "Gaddis", 400);

	for (int i=0; i<2; i++)
	{
		cout<<"Input the title of the book: ";
		getline(cin, title);
		cout<<"Input the author of the book: ";
		getline(cin, author);
		cout<<"Input the price of the book: ";
		cin>>price;
		cin.ignore();

		books[nrOFBooks++] = new Book(title, author, price);
	}

	cout<<"This is the books in the array: "<<endl;
	for (int i=0; i<capacity; i++)
	{
		cout<<books[i]->toString()<<endl;
	}

	for (int i=0; i<nrOFBooks; i++)
	{
		delete books[i];  // deleting Book object
	}

	delete [] books;  // deleting array

	return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值