题目要求如下:
定义一个course类,该类中有私有数据成员char*型指针
introduction和整型课号ID,要求在构造函数里申请动态内存来存
放课程介绍,并实现该类的拷贝构造函数。
实现拷贝功能的函数如下:
- Course(const Course& P) //拷贝函数,实现深拷贝
- {
- Introduction = new char(*P.Introduction); //通过使用new来申请动态内存
- ID = P.ID;
- introduction = new char(*P.introduction); //通过使用new来申请动态内存
- id = P.id;
- }
- 实现动态内存释放的析构函数如下:
- ~Course() //析构函数
- {
- if (introduction != NULL)
- {
- delete introduction; //释放new申请的动态内存
- introduction = NULL;
- }
- if (Introduction != NULL)
- {
- delete Introduction; //释放new申请的动态内存
- Introduction = NULL;
- }
- }
- 代码运行过程:第一次传递数值是调用默认构造函数,当把第一次传递的参数要拷贝时,调用盛拷贝函数。例如:
- Course P1(ch, n);
- cout << "P1 Introduction:" << *P1.introduction << " P1 ID:" << P1.id << endl;
- 执行之一过程是不会调用深拷贝函数,当进行一下步骤时才会调用深拷贝函数
- Course P2(P1);
- cout << "P2 Introduction:" << *P2.introduction<< " P2 ID:" << P2.id<< endl;
- 要注意输出是要用“*”符号获取该地址上的有关参数。
完整的代码如下:仅供参考
- #include<iostream>
- #include<string>
- using namespace std;
- //定义Course类
- class Course
- {
- private: //定义两个私有变量Introduction和ID
- char* Introduction;
- int ID;
- public: //定义公有变量
- char* introduction;
- int id;
- Course(char x, int n) //有参构造函数
- {
- Introduction = new char(x);
- ID = n;
- introduction = new char(x);
- id = n;
- }
- ~Course() //析构函数
- {
- if (introduction != NULL)
- {
- delete introduction; //释放new申请的动态内存
- introduction = NULL;
- }
- if (Introduction != NULL)
- {
- delete Introduction; //释放new申请的动态内存
- Introduction = NULL;
- }
- }
- Course(const Course& P) //拷贝函数,实现深拷贝
- {
- Introduction = new char(*P.Introduction);
- ID = P.ID;
- introduction = new char(*P.introduction);
- id = P.id;
- }
- };
- void test1()
- {
- char ch;
- int n;
- cin >> ch >> n; //第一次输入ch和n
- Course P1(ch, n);
- cout << "P1 Introduction:" << *P1.introduction << " P1 ID:" << P1.id << endl;
- Course P2(P1);
- cout << "P2 Introduction:" << *P2.introduction<< " P2 ID:" << P2.id<< endl;
- cin >> ch >> n; //第二次输入ch和n
- Course P3(ch, n);
- cout << "P3 Introduction:" << *P3.introduction<< " P3 ID:" << P3.id << endl;
- Course P4(P3);
- cout << "P4 Introduction:" << *P4.introduction << " P4 ID:" << P4.id << endl;
- }
- int main()
- {
- test1();
- return 0;
- }