(3).定义一个学生类stu,要求里面有学号,姓名(字符指针类型)2种数据成员,要求写如下成员函数:构造函数,拷贝构造函数,析构函数,显示函数。在主程序中定义stu的50个数组元素的数组对象,测试上面的类。 C++提交的答案将被附加下面的main函数,提交时请不要包含main函数。 int main() { stu s[50]; stu s2("x",1); for(int i=0;i<5;i++) s[i].display(); stu s1(s2); s2.display(); s1.display(); return 0; } 样例输入 复制 no 样例输出 复制 no name 0 no name 0 no name 0 no name 0 no name 0 x 1 x 1
时间: 2024-01-16 14:05:11 浏览: 137
以下是实现上述要求的代码:
```cpp
#include <iostream>
#include <cstring>
using namespace std;
class stu {
private:
int id;
char* name;
public:
// 构造函数
stu() {
id = 0;
name = new char[3];
strcpy(name, "no");
}
stu(char* n, int i) {
id = i;
name = new char[strlen(n) + 1];
strcpy(name, n);
}
// 拷贝构造函数
stu(const stu& s) {
id = s.id;
name = new char[strlen(s.name) + 1];
strcpy(name, s.name);
}
// 析构函数
~stu() {
delete[] name;
}
// 显示函数
void display() {
cout << name << " " << id << endl;
}
};
int main() {
stu s[50];
stu s2("x",1);
for(int i=0; i<5; i++) {
s[i].display();
}
stu s1(s2);
s2.display();
s1.display();
return 0;
}
```
输出结果为:
```
no 0
no 0
no 0
no 0
no 0
x 1
x 1
```
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.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://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)