<pre name="code" class="cpp">//《C++教程》郑莉、李宁,人民邮电出版社,2010第一版
//第五章 抽象与分类
//简单的学生信息系统,有录入、查询、输出功能
//BUG:<span style="font-family: Arial, Helvetica, sans-serif;"> </span>
#include "stdafx.h"
#include<iostream>
#include<string>
using namespace std;
class Student{
private:
string strName;//姓名
unsigned long nIndex;//学号
int nScore;//成绩
public:
Student(string _name="somebody",unsigned long _index=2008010001,int _score=100):strName(_name),nIndex(_index),nScore(_score){}//构造函数初始化列表
~Student(){}
string getName();
unsigned long getIndex();
int getScore();
void setName(string strNameNew);
void setIndex(unsigned long nIndexNew);
void setScore(int nScoreNew);
};
string Student::getName(){
return strName;
}
unsigned long Student::getIndex(){
return nIndex;
}
int Student::getScore(){
return nScore;
}
void Student::setName(string strNameNew){
strName = strNameNew;
}
void Student::setIndex(unsigned long nIndexNew){
nIndex = nIndexNew;
}
void Student::setScore(int nScoreNew){
nScore = nScoreNew;
}
//遍历查询函数
void Query(bool &flag,Student *sList,int size){
unsigned long index;
unsigned long num;
char yOrN;
bool isFound = false;
cout<<"请输入要查询的学生学号:";
cin>>index;
for (int i = 0;i<size;i++)
{
num = sList[i].getIndex();
if (num == index)
{
cout<<"姓名:"<<sList[i].getName()<<endl;
cout<<"学号:"<<sList[i].getIndex()<<endl;
cout<<"成绩:"<<sList[i].getScore()<<endl;
isFound = true;
break;
}
}
if (!isFound)
{
cout<<"该学号信息不存在!"<<endl;
}
cout<<"是否继续查询?(y/n):";
cin>>yOrN;
if (yOrN == 'y'||yOrN == 'Y')
{
flag = true;
}
if (yOrN == 'n'||yOrN == 'N')
{
flag = false;
}
}
//输出函数
void printAll(Student *sList,int size){
for (int i=0;i<size;i++)
{
cout<<"姓名:"<<sList[i].getName();
cout<<"\t学号:"<<sList[i].getIndex();
cout<<"\t成绩:"<<sList[i].getScore()<<endl;
}
}
int main(int argc, char* argv[])
{
Student *sList;
int size;//要录入信息的学生个数
string _name;
unsigned long _index;
int _score;
cout<<"请输入学生总数:";
cin>>size;
<span style="color:#ff0000;">sList = new Student[size];//BUG:一开始没有这句,所以运行起来后提示的错误信息是"The variable 'sList' is being used without being initialized"</span>
for (int i=0;i<size;i++)
{
cout<<"学生姓名:";
cin>>_name;
cout<<"学生学号:";
cin>>_index;
cout<<"学生分数:";
cin>>_score;
sList[i] = Student(_name,_index,_score);
}
bool flag = false;
char YorN;
cout<<"是否进行查询?(y/n):";
cin>>YorN;
if (YorN == 'y'||YorN == 'Y')
{
flag = true;
}
while (flag)
{
Query(flag,sList,size);
}
cout<<"------------------------"<<endl;//当查询结束,自动打印出所有学生信息
cout<<"所有学生数据"<<endl;
printAll(sList,size);
return 0;
}
唉,指针不初始化就不能用,犯了多少次还是会出这种弱智错误,我真是个傻X……╭(╯^╰)╮。谨记于此,以备后忘。