C++ new和delete操作符

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操作符

上一篇:c++中string类和vector类比较


下一篇:c++ 笔试题2