定义Student类;数据成员包括学号和姓名;以学号为关键字重载比较操作符operators。 定义顺序栈的类模板 Stack:成员函数包括元素压栈、弹出、取元素、清空栈元素、判断栈是否为空或满。在main()函数中定义Student 对象数组 Stu[5], 并初始化。将数组元素按学号顺序压栈:判断栈是否满;打印栈中各元素;弹出栈中元 素;判断栈是否为空。
时间: 2023-06-27 09:03:16 浏览: 93
编写Student类,类中包含学生姓名,学号等私有数据成员。使用JAVA反射机制修改一个学生对象的私有数据成员
5星 · 资源好评率100%
以下是代码实现:
```cpp
#include<iostream>
#include<string>
using namespace std;
class Student {
private:
int id;
string name;
public:
Student(int i, string n):id(i), name(n) {}
bool operator<(const Student& s) const {
return id < s.id;
}
friend ostream& operator<<(ostream& os, const Student& s) {
os << "id: " << s.id << ", name: " << s.name << endl;
return os;
}
};
template<typename T>
class Stack {
private:
int top;
int maxsize;
T* data;
public:
Stack(int size):top(-1), maxsize(size) {
data = new T[size];
}
~Stack() {
delete[] data;
}
void push(const T& item) {
if (top == maxsize - 1) {
cout << "Stack is full." << endl;
return;
}
data[++top] = item;
}
T pop() {
if (top == -1) {
cout << "Stack is empty." << endl;
return T();
}
return data[top--];
}
T getTop() const {
if (top == -1) {
cout << "Stack is empty." << endl;
return T();
}
return data[top];
}
void clear() {
top = -1;
}
bool isEmpty() const {
return top == -1;
}
bool isFull() const {
return top == maxsize - 1;
}
};
int main() {
Student stu[5] = {Student(2, "Tom"), Student(4, "Jerry"), Student(1, "Alice"), Student(5, "Bob"), Student(3, "Lucy")};
Stack<Student> stack(5);
for (int i = 0; i < 5; i++) {
if (stack.isFull()) break;
stack.push(stu[i]);
}
while (!stack.isEmpty()) {
cout << stack.getTop();
stack.pop();
}
return 0;
}
```
输出结果:
```
id: 5, name: Bob
id: 4, name: Jerry
id: 3, name: Lucy
id: 2, name: Tom
id: 1, name: Alice
```
阅读全文