safearray.h文件
#ifndef SAFEARRAY_H
#define SAFEARRAY_H
#include
template
class safearray {
private:
T* storage;
int capacity;
public:
safearray() : storage(NULL), capacity(0) {} // default constructor
safearray(const safearray& c){
capacity=c.capacity;
storage=new T;
storage=(c.storage);
};
safearray(int); // single param constructor
~safearray(void); // destructor
T& operator throw(out_of_range);
};
template
safearray::safearray(int i):capacity(i),storage(new T[i])
{}
template
safearray::~safearray()
{
delete [] storage;
}
template
T& safearray::operator throw(out_of_range)
{
if(i(capacity-1)){
out_of_range e("The index is out of range of array");
throw e;
}else
return storage[i];
}
#endif
course头文件
#ifndef COURSE_H
#define COURSE_H
#include "safearray.h"
const int MAX_LINES = 10;
class course {
public:
string name;
string title;
//string description[MAX_LINES];
safearray description;
course()
{
name="";
title="";
description=safearray<string>(MAX_LINES);
}
course(string name, string title)
{
name=name;
title=title;
description=safearray<string>(MAX_LINES);
}
friend ostream& operator<<(ostream&,const course&);
friend istream& operator>>(istream&, course&);
};
ostream& operator<<(ostream& out, course& c) {
out << c.name << ": " << c.title << "\n";
int index = 0;
while (c.description[index] != "") {
out << c.description[index++] << "\n";
}
return out;
}
istream& operator>>(istream& in, course& c) {
getline(in, c.name);
getline(in, c.title);
string line;
getline(in, line);
int number = 0;
while (line != "") {
c.description[number++] = line;
getline(in, line);
}
return in;
}
#endif
main.cpp
// For Visual C++ users:
// Visual C++ does not implement checked exceptions, and the compiler will
// show warning messages when functions throws exceptions. The following
// warning pragma ignore those compiler messages.
//
// GCC users can remove this #pragma warning.
#pragma warning(disable: 4290)
#include
#include
#include
#include
using namespace std;
#include "course.h"
#include "safearray.h"
void init_courses(safearray&);
void display_menu(safearray);
const int NUM_COURSES = 10;
const int QUIT = 99;
int main(int argc, char* argv[]) {
safearray<course> courses(NUM_COURSES);
init_courses(courses);
int choice = 0;
while (choice != QUIT) {
display_menu(courses);
cout << "Enter number of course to see more information on\n";
cin >> choice;
cout << "\n";
if (choice >= 1 && choice <= NUM_COURSES) {
cout << courses[choice - 1] << "\n\n";
}
}
return EXIT_SUCCESS;
}
void display_menu(safearray courses) {
for (int i = 1; i <= NUM_COURSES; i++) {
cout << i << ". " << courses[i - 1].name << "\n";
}
cout << "99. Quit\n";
}
void init_courses(safearray& courses) {
ifstream inf("courses.txt");
if (! inf) {
cerr << "Could not open courses.txt" << endl;
exit(EXIT_FAILURE);
}
for (int i = 0; i < NUM_COURSES; i++) {
inf >> courses[i];
}
inf.close();
}
求大神来帮帮忙,