引自免费微信小程序:皆我百晓生
为了满足上述的学生会组织机构管理问题设计方案,我们将逐步构建所需的类和函数。首先,我们需要创建一个表示学生信息的Student类,然后是表示树节点的通用模板类Node,接着是表示整个学生会组织的类Organization,最后编写主函数实现用户交互与功能调用。
以下是具体的代码实现:
#include
#include
// 定义学生类
class Student {
public:
// 构造函数
Student(const std::string& position, const std::string& name, char gender, int grade, int classNo)
: position_(position), name_(name), gender_(gender), grade_(grade), classNo_(classNo) {}
// 获取学生信息的方法
const std::string& getPosition() const { return position_; }
const std::string& getName() const { return name_; }
char getGender() const { return gender_; }
int getGrade() const { return grade_; }
int getClassNo() const { return classNo_; }
private:
std::string position_;
std::string name_;
char gender_;
int grade_;
int classNo_;
};
// 定义树节点类
template
class Node {
public:
// 有参构造函数
Node(T* data) : data_(data), first_child_(nullptr), brother_(nullptr) {}
// 无参析构函数
~Node() {}
// 获取第一个孩子节点
Node* getFirstChild() const { return first_child_; }
// 设置第一个孩子节点
void setFirstChild(Node* node) { first_child_ = node; }
// 获取右兄弟节点
Node* getBrother() const { return brother_; }
// 设置右兄弟节点
void setBrother(Node* node) { brother_ = node; }
// 获取数据域
T* getData() const { return data_; }
// 设置数据域
void setData(T* data) { data_ = data; }
private:
T* data_;
Node* first_child_;
Node* brother_;
};
// 定义学生会组织类
class Organization {
public:
// 插入学生到部门
void insertStudent(const Student* student, Node* department) {
if (!department) {
throw std::runtime_error("Invalid department.");
}
Node* new_node = new Node(student);
if (!department->getFirstChild()) {
department->setFirstChild(new_node);
} else {
Node* current = department->getFirstChild();
while (current->getBrother()) {
current = current->getBrother();
}
current->setBrother(new_node);
}
}
// 删除学生
void removeStudent(const Student* student, Node* department) {
if (!department) {
throw std::runtime_error("Invalid department.");
}
Node* current = department->getFirstChild();
Node* previous = nullptr;
while (current && current->getData() != student) {
previous = current;
current = current->getFirstChild();
}
if (!current) {
throw std::runtime_error("Student not found.");
}
if (previous) {
previous->setFirstChild(current->getFirstChild());
} else {
department->setFirstChild(current->getFirstChild());
}
if (current->getBrother()) {
current->getBrother()->setBrother(current->getFirst
