类类型 /声明一个学生类类型: 数据成员:姓名(Char”)、年龄(short): 提供:构造函数、析构函数、拷贝构造函数; 功能:实现对一名学生信息的输入输出、实现对20名学生信息的输入输出。
时间: 2023-05-24 14:03:28 浏览: 73
以下是一个实现上述要求的学生类类型的示例代码:
```
#include <iostream>
#include <cstring>
class Student {
public:
// 构造函数
Student(const char* _name = "", short _age = 0) {
// 分配内存存储姓名
name = new char[strlen(_name) + 1];
strcpy(name, _name);
age = _age;
}
// 拷贝构造函数
Student(const Student& other) {
// 分配内存存储姓名
name = new char[strlen(other.name) + 1];
strcpy(name, other.name);
age = other.age;
}
// 析构函数
~Student() {
delete[] name;
}
// 输入学生信息
void input() {
std::cout << "请输入学生姓名:";
std::cin >> name;
std::cout << "请输入学生年龄:";
std::cin >> age;
}
// 输出学生信息
void output() const {
std::cout << "姓名:" << name << ",年龄:" << age << std::endl;
}
private:
char* name; // 姓名
short age; // 年龄
};
int main() {
Student students[20];
// 输入20个学生信息
for (int i = 0; i < 20; ++i) {
std::cout << "请输入第" << i+1 << "个学生信息:" << std::endl;
students[i].input();
}
// 输出20个学生信息
for (int i = 0; i < 20; ++i) {
std::cout << "第" << i+1 << "个学生信息为:" << std::endl;
students[i].output();
}
return 0;
}
```