我在大学里用 C++ 练习过。所以他们要求我制作一个复制构造函数和一个重载赋值运算符 = 的课程。所以我做到了,而且效果很好。他们说我在方法 get() 和我的复制构造函数以及重载赋值运算符上是错误的。不幸的是,练习效果很好。他们也没有要求 main()。
#include <iostream>
using namespace std;
class DIcourse{
private:
int *ids;
int numstudents;
char *title;
char *description;
public:
DIcourse();
~DIcourse();
DIcourse(const DIcourse &tmp);
DIcourse operator=(const DIcourse &tmp);
int const get_num();
char const *get_title();
char const *get_description();
int const *get_ids();
int set_num_ids(int num);
char set_description(char *tmp);
char set_title(char *temp);
};
DIcourse :: DIcourse(){
ids=NULL;
numstudents=0;
title=new char[50];
description=new char[200];
}
DIcourse :: ~DIcourse(){
delete [] ids;
delete [] title;
delete [] description;
}
DIcourse :: DIcourse(const DIcourse& tmp){
numstudents=tmp.numstudents;
ids=new int[numstudents];
for(int i=0;i<numstudents;i++){
ids[i]=tmp.ids[i];
}
title=tmp.title;
description=tmp.description;
}
DIcourse DIcourse::operator=(const DIcourse &tmp){
delete [] ids;
numstudents=tmp.numstudents;
ids=new int[numstudents];
for(int i=0;i<numstudents;i++){
ids[i]=tmp.ids[i];
}
delete[] description;
delete[] title;
description= new char[200];
title= new char[50];
description=tmp.description;
title=tmp.title;
return *this;
}
const int DIcourse :: get_num(){
return numstudents;
}
const char* DIcourse :: get_title(){
return title;
}
const char* DIcourse :: get_description(){
return description;
}
const int* DIcourse :: get_ids(){
return ids;
}
int DIcourse :: set_num_ids(int num){
numstudents++;
int *temp_array;
temp_array=new int[numstudents];
temp_array[numstudents-1]=num;
if(ids!=NULL){
for(int i=0; i<numstudents-1; i++){
temp_array[i]=ids[i];
}
delete [] ids;
}
ids=temp_array;
}
char DIcourse :: set_description(char *tmp){
int i=0;
while(tmp[i]!='\0'){
description[i]=tmp[i];
i++;
}
description[i]='\0';
}
char DIcourse :: set_title(char *temp){
int i=0;
while(temp[i]!='\0'){
title[i]=temp[i];
i++;
}
title[i]='\0';
}