过去的c++作业现在把它贴出来 其中主要是用到了拷贝构造函数和赋值运算符重载以及深拷贝这些知识。程序虽然很简单,但还是有一些价值的。 /**//* version: 1.0 author: LSK date: 2006.10.26*/#include <iostream.h>#include <string.h>#define max 20class Gooles //定义Gooles类也就是商品类...{ private: //私有数据成员日期 char* date; int length; //私有数据成员日期长度 public: Gooles(char* string) ...{ if(string) ...{ length = strlen(string); date = new char[length + 1]; strcpy(date,string); } else ...{ length = 0; date = 0; } } void printGooles() ...{ cout<<"正在向货架中添加,商品的生产日期是: "<<date<<" "; } Gooles& operator = (const Gooles& str) //赋值运算符重载 ...{ delete date; //防止内存泄漏 length = strlen(str.date); date = new char[length + 1]; strcpy(date, str.date); return *this; } Gooles(Gooles& str) //拷贝构造函数 ...{ length = str.length; date = new char[length + 1]; strcpy(date, str.date); } Gooles() //必须提供Gooles()的无参构造函数 ...{ date = 0; length = 0; } ~Gooles() ...{ delete[]date; }};class MyStack //定义货架类...{ private: Gooles thing[max]; //对象数组作为私有数据成员 int top; //栈顶指针 public: MyStack() ...{ top = 0; } Gooles pop() ...{ top--; return thing[top]; } void push(const Gooles& element) ...{ thing[top++] = element; //调用了赋值运算符重载 } bool ifEmpty() ...{ if(top == 0) return true; else return false; } Gooles* getTop() ...{ if(top == 0) ...{ cout<<"货架已空"<<" "; return 0; } else return &thing[top-1]; } ~MyStack() ...{ } };main()...{ Gooles first("2006.4.3"); //分别实例化货物 Gooles second("2006.5.6"); Gooles thread("2006.6.5"); Gooles fhouth("2006.7.3"); Gooles fifth("2006.9.10"); Gooles sixth("2006.10.10"); MyStack mystack,mystore; mystack.push(first); //将货物逐个放入缓冲的堆栈中 mystack.push(second); mystack.push(thread); mystack.push(fhouth); mystack.push(fifth); mystack.push(sixth); cout<<"货架程序启动.....新货先被添加进货架底部" <<endl; int i=0; while(!mystack.ifEmpty()) ...{ Gooles temp=mystack.pop(); //调用了拷贝构造函数对对象temp赋值 mystore.push(temp); Gooles *p=mystore.getTop(); cout<<"进入货架的顺序是:"<<++i <<endl; p->printGooles(); }}