编写一个类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
}