马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
如果Student& Studentlist::operator[](char *name);这个函数没能学生列表中找到匹配的学生,它会返回什么东西呢?
#include<iostream>
#include<string.h>
using namespace std;
class Student { // 学生的数据域,存放学生的信息
public:
int sno;
char sname[10];
};
class NodeStudent { // 学生链表节点
public:
Student data;
NodeStudent *next;
};
class Studentlist {
private:
NodeStudent* head; // 学生链表的头
NodeStudent* rear; // 学生列表的尾巴
int itemCount; // 学生的数量
public:
Studentlist(); // 初始化头指针
~Studentlist(); // 释放学生列表
Student& operator[](char *name); // 重载运算符[], 参数为字符串,返回Student引用
void add(Student s); // 增加一个学生,放入链表
void print(); // 打印所有学生
};
Student& Studentlist::operator[](char *name) {
NodeStudent *p(head->next);
while(p){
if(strcmp(p->data.sname, name) == 0) {
return p->data;
}
}
}
本帖最后由 傻眼貓咪 于 2022-3-19 15:19 编辑
试试这个: #include <iostream>
#include <cstring>
class Student {
public:
int ID{}; // Warning C26495 Variable 'Student::ID' is uninitialized.Always initialize a member variable(type.6).
std::string name;
};
class Node {
public:
Student data;
Node* next{}; // Warning C26495 Variable 'Node::next' is uninitialized.Always initialize a member variable(type.6).
};
class StudentsList {
private:
Node* head;
size_t size;
public:
StudentsList();
StudentsList(Student*);
~StudentsList();
Student& operator[](std::string name);
void add(Student*);
void print();
};
StudentsList::StudentsList() {
head = NULL;
size = 0;
}
StudentsList::StudentsList(Student *stu) {
Node* tail = NULL;
head = new Node;
head->data = { stu->ID, stu->name };
head->next = tail;
size = 1;
}
StudentsList::~StudentsList() {
Node* p;
if (head) {
p = head;
head = head->next;
delete p;
}
delete head;
}
Student& StudentsList::operator[](std::string name) {
Node* p;
if (head) {
p = head;
while (p) {
if (!(strcmp(p->data.name.c_str(), name.c_str()))) {
return p->data;
}
p = p->next;
}
}
std::cout << "访问未找到匹配名字 (name)" << std::endl;
static Student stu; // 静态 <------------- 注意这里 -------------
return stu; // 返回结构体 <------------- 注意这里 -------------
}
void StudentsList::add(Student* stu) {
Node* tail;
tail = head;
head = new Node;
head->data = { stu->ID, stu->name };
head->next = tail;
size++;
}
void StudentsList::print() {
Node* p;
if (head) {
p = head;
while (p) {
std::cout
<< p->data.ID
<< " "
<< p->data.name
<< std::endl;
p = p->next;
}
}
else {
std::cout << "linked list is empty" << std::endl;
}
}
int main() {
return 0;
}
|