首页 > 编程语言 > 详细

C++ new和delete操作符

时间:2014-03-01 06:16:25      阅读:514      评论:0      收藏:0      [点我收藏+]

const指针 防止指针指向的内容被修改

#include<iostream>
#include<string>
using namespace std;

struct Elephant{
	string name;
	Elephant* next;
};

void print_elephants(const Elephant* ptr);
Elephant* get_elephants();
void free_list(const Elephant* ptr);

int main()
{
	Elephant* start;
	start = get_elephants();
	print_elephants(start);
	free_list(start);
	return 0;
}

Elephant* get_elephants(){
	Elephant *current, *first;
	int response;
	current=first=new Elephant;
	cout<<"\nName: ";
	cin>>current->name;
	cout<<endl<<"add? 1=Yes 0=No"<<endl;
	cin>>response;
	while(response == 1)
	{
		current = current->next = new Elephant;
		cout<<"\nName: ";
		cin>>current->name;
		cout<<endl<<"add? 1=Yes 0=No"<<endl;
		cin>>response;
	}
	current->next = 0;
	return first;
}

void print_elephants(const Elephant* ptr)
{

	while(ptr)
	{
		cout<<ptr->name<<endl;
		ptr = ptr->next;
	}
}

void free_list(const Elephant* ptr)
{
	const Elephant* temp_ptr;
	while(ptr)
	{
		temp_ptr = ptr->next;
		delete ptr;
		ptr= temp_ptr;
	}
}


C++ new和delete操作符,布布扣,bubuko.com

C++ new和delete操作符

原文:http://blog.csdn.net/slience_perseverance/article/details/20123889

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!