fork download
  1. #include<iostream>
  2. #include<cstring>
  3. using namespace std;
  4. class CHuman{
  5. private:
  6. char* mName;
  7. int mAge;
  8. public:
  9. CHuman(){
  10. mAge = 0;
  11. }
  12. ~CHuman(){
  13. mAge = 0;
  14. //delete[] mName; // 請問這個delete[] 是成功運作的嗎? //delete之後結果會出問題,程式會直接結束
  15. }
  16. void SetName(const char* name){
  17. mName = new char[strlen(name)+1];
  18. strcpy(mName, name);
  19. }
  20. char* GetName(){
  21. return mName;
  22. }
  23. void SetAge(int age){
  24. mAge = age;
  25. }
  26. int GetAge(){
  27. return mAge;
  28. }
  29. };
  30. class CEmployee: public CHuman{
  31. private:
  32. char* mId;
  33. public:
  34. CEmployee(){
  35. }
  36. ~CEmployee(){
  37. }
  38. void SetId(const char* id){
  39. mId = new char[strlen(id)+1];
  40. strcpy(mId, id);
  41. }
  42. char* GetId(){
  43. return mId;
  44. }
  45. };
  46. class CEmployees{
  47. private:
  48. CEmployee* mEmployees;
  49. int count;
  50. public:
  51. CEmployees(){
  52. count = 0;
  53. mEmployees = new CEmployee[count+1];//請問這行可以省略嗎 如果不在建構的時候就設置空間 是不是就不能成功Add第一筆
  54. }
  55. ~CEmployees(){
  56. delete[] mEmployees;
  57. }
  58. void Add(const CEmployee Employee){
  59. CEmployee* NewEmployees;
  60. NewEmployees = new CEmployee[count+1];
  61. for(int index=0; index<count; ++index){
  62. NewEmployees[index] = mEmployees[count];
  63. }
  64. delete[] mEmployees;
  65. mEmployees = new CEmployee[count+1];
  66. mEmployees = NewEmployees;
  67. mEmployees[count] = Employee;
  68. count++;
  69. }
  70. CEmployee Get(char* id){
  71. for(int index=0; index<count; ++index){
  72. if(strcmp(id, mEmployees[index].GetId()) == 0)
  73. return mEmployees[index];
  74. }
  75. return CEmployee();
  76. }
  77. };
  78. int main(){
  79. CEmployee Employee;
  80. CEmployees Employees;
  81. int act;
  82. while(1){
  83. cout<<"1.新增員工\n2.查詢員工\n請輸入數字: ";
  84. cin>>act;
  85. if(act!=3){
  86. switch(act){
  87. case 1:{
  88. char* name = new char[1];
  89. char* id = new char[1];
  90. int age = 0;
  91. cout<<"請輸入資料!\n姓名: ";
  92. cin>>name;
  93. Employee.SetName(name);
  94. cout<<"年齡: ";
  95. cin>>age;
  96. Employee.SetAge(age);
  97. cout<<"員工ID: ";
  98. cin>>id;
  99. Employee.SetId(id);
  100. Employees.Add(Employee);
  101. cout<<"Finish !\n";
  102. break;
  103. }
  104. case 2:{
  105. char* id = new char[1];
  106. cout<<"請輸入要查詢的員工ID: ";
  107. cin>>id;
  108. cout<<"姓名\t年齡\t員工ID\n";
  109. cout<<Employees.Get(id).GetName()<<"\t"<<Employees.Get(id).GetAge()<<"\t"<<Employees.Get(id).GetId()<<endl;
  110. break;
  111. }
  112. }
  113. }
  114. else
  115. break;
  116. }
  117. return 0;
  118. }
  119.  
  120.  
Success #stdin #stdout 0s 4420KB
stdin
1
kevin 19 A99999
2
A99999
3
stdout
1.新增員工
2.查詢員工
請輸入數字: 請輸入資料!
姓名: 年齡: 員工ID: Finish !
1.新增員工
2.查詢員工
請輸入數字: 請輸入要查詢的員工ID: 姓名	年齡	員工ID
kevin	19	A99999
1.新增員工
2.查詢員工
請輸入數字: