用C++定义学生类,并在主函数定义类的对象进行调用测试。要求: // //① 数据成员,参考实验3。 // //② 具有无参和有参的构造函数。 // //③ 具有深拷贝构造函数。(选做) // //④ 具有析构函数。 // //⑤ 具有输出函数、排序函数等。(选做内容:排序函数)
时间: 2023-12-05 21:05:15 浏览: 51
以下是C++定义学生类的示例代码,并在主函数定义类的对象进行调用测试:
```cpp
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
class Student {
private:
string name;
int age;
string gender;
string major;
public:
// 无参构造函数
Student() {
name = "";
age = 0;
gender = "";
major = "";
}
// 有参构造函数
Student(string n, int a, string g, string m) {
name = n;
age = a;
gender = g;
major = m;
}
// 深拷贝构造函数
Student(const Student& s) {
name = s.name;
age = s.age;
gender = s.gender;
major = s.major;
}
// 析构函数
~Student() {
cout << "Object is being deleted" << endl;
}
// 输出函数
void display() {
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
cout << "Gender: " << gender << endl;
cout << "Major: " << major << endl;
}
// 排序函数
static bool compare(Student s1, Student s2) {
return s1.age < s2.age;
}
};
int main() {
// 定义对象并调用函数
Student s1("Tom", 20, "Male", "Computer Science");
s1.display();
// 调用排序函数
Student s2("Jerry", 18, "Male", "Mathematics");
Student s3("Alice", 22, "Female", "Physics");
Student s4("Bob", 19, "Male", "Chemistry");
Student arr[] = {s1, s2, s3, s4};
sort(arr, arr+4, Student::compare);
for (int i = 0; i < 4; i++) {
arr[i].display();
}
return 0;
}
```