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; } }