編寫一個類Sequence,在自由存儲區中按照升序存儲整數值的遞增序列。序列的長度和起始值在構造函數中提供。確保該序列至少有兩個值,默認有10個值,從0開始(0,1,2,3,4,5,6,7,8,9)。需要有足夠的內存空間來存儲該序列,再用要求的值填充內存。
提供show()函數列出該序列,以確保正確創建Sequence對象。
確保在銷毀Sequence對象時,釋放分配給序列的內存(注意:確保釋放所有的內存!)。
創建并輸出5個隨機長度(長度有限!)的序列和一個默認序列,來演示這個類的操作。
本題主要用到的技術點有:類的內部動態分配內存,類的析構函數等。

Sequence.h
// Sequence.h
#ifndef SEQUENCE_H
#define SEQUENCE_H
// Class encapsulating a sequence of integers
class Sequence {
public:
Sequence(); // Default constructor
Sequence(int start, int length = 2); // Constructor
~Sequence(); // Desctructor
void show(); // Output a sequence
private:
int* pSequence; // Pointer to a sequence
int length; // Sequence length
};
#endif

Sequence.cpp
// Sequence.cpp
// Implementation of the Sequence class
// encapsulating an arbitrary length sequence of integers
#include "Sequence.h"
#include <iostream>
#include <iomanip>
using std::cout;
using std::endl;
// Default constructor
Sequence::Sequence() {
length = 10;
pSequence = new int[length];
for (int i=0; i<length; i++)
pSequence[i] = i;
}
Sequence::Sequence(int start, int length) {
this->length = length < 2 ? 2 : length;
pSequence = new int[length];
for (int i=0; i<length; i++)
pSequence[i] = start+i;
}
// Destructor
Sequence::~Sequence() {
cout << "Destructor called." << endl;
delete[] pSequence;
}
// Output a sequence
void Sequence::show() {
for(int i=0; i<length; i++) {
if (i%10 == 0)
cout << endl;
cout << std::setw(2+(pSequence[0]+length)/10) << pSequence[i];
}
cout << endl;
}

main.cpp
#include <iostream>
#include <cstdlib>
#include <ctime>
using std::cout;
using std::endl;
#include "Sequence.h"
// Function to generate a random integer from start to end
inline int random(int start, int end) {
return start +
static_cast<int>(
(end*static_cast<long>(
rand()))/(RAND_MAX+1L));
}
void main() {
srand((unsigned)time(0)); //Initialize the random number generator
const int nSeq = 5;
Sequence** pSequences = new Sequence*[nSeq];
for (int i=0; i<nSeq; i++) {
// Generate a sequence with a random start and length
pSequences[i] = new Sequence(random(1, 50), random(2, 10));
cout << endl << "Sequence " << i+1 << ":";
pSequences[i]->show(); //Output the sequence
}
// Now the default sequence
Sequence sequence;
cout << endl << "Default sequence :";
sequence.show(); //Output the default sequence
// First delete the Sequence objects in the free store
for (int j=0; j<nSeq; j++)
delete pSequences[j];
delete[] pSequences; // Now delete the array holding their addresses
}