c++ 设计一个Student 类,其属性包括:学号sno、姓名name 以及性别sex,分别利用student 类构造西数和拷贝构造西数建立对象,打印每个student 类对象的信息。要求分别编写浅拷贝构造函数和深拷贝构造西数两种不同实现版本的程序。
时间: 2024-02-19 08:03:43 浏览: 53
好的,我来为您编写这个程序。
首先,我们需要定义一个Student类,其中包含学号、姓名和性别三个属性:
```c++
#include <iostream>
#include <cstring>
class Student {
public:
Student(const char* sno, const char* name, const char* sex);
Student(const Student& stu);
~Student();
void print();
private:
char* m_sno;
char* m_name;
char* m_sex;
};
```
上面的代码中,我们定义了两个构造函数,一个是常规构造函数,另一个是拷贝构造函数;还定义了一个析构函数用于释放内存;最后定义了一个print()函数用于打印学生信息。
接下来,我们来实现浅拷贝构造函数:
```c++
Student::Student(const Student& stu) {
m_sno = stu.m_sno;
m_name = stu.m_name;
m_sex = stu.m_sex;
}
```
上面的代码中,我们将原对象的指针直接赋值给新对象,这样会导致两个对象的指针指向同一个内存地址,当其中一个对象被销毁时,会导致另一个对象的指针变为野指针,从而导致程序崩溃。
为了避免这种情况,我们需要实现深拷贝构造函数:
```c++
Student::Student(const Student& stu) {
m_sno = new char[strlen(stu.m_sno) + 1];
strcpy(m_sno, stu.m_sno);
m_name = new char[strlen(stu.m_name) + 1];
strcpy(m_name, stu.m_name);
m_sex = new char[strlen(stu.m_sex) + 1];
strcpy(m_sex, stu.m_sex);
}
```
上面的代码中,我们先为新对象的属性分配内存,然后将原对象的属性值复制到新对象的属性中,这样就避免了两个对象共享同一个内存地址的问题。
最后,我们还需要实现常规构造函数、析构函数和print()函数:
```c++
Student::Student(const char* sno, const char* name, const char* sex) {
m_sno = new char[strlen(sno) + 1];
strcpy(m_sno, sno);
m_name = new char[strlen(name) + 1];
strcpy(m_name, name);
m_sex = new char[strlen(sex) + 1];
strcpy(m_sex, sex);
}
Student::~Student() {
delete[] m_sno;
delete[] m_name;
delete[] m_sex;
}
void Student::print() {
std::cout << "sno: " << m_sno << ", name: " << m_name << ", sex: " << m_sex << std::endl;
}
```
这样,一个完整的Student类就编写完成了。我们可以编写一个测试程序来测试一下:
```c++
int main() {
Student s1("001", "Tom", "Male");
Student s2(s1);
s1.print();
s2.print();
return 0;
}
```
上面的代码中,我们先创建了一个s1对象,然后通过拷贝构造函数创建了一个s2对象,最后分别调用了它们的print()函数,输出了它们的信息。
如果使用的是浅拷贝构造函数,那么输出的结果会相同,因为它们共享同一个内存地址;如果使用的是深拷贝构造函数,那么输出的结果会不同,因为它们拥有不同的内存地址。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)