接类的操作练习一、二
重新编写比较函数,把它作为Sequence类的一个友元。如何改变参数和调用该函数的方式?最好使用什么技术?
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
//bool equals(const Sequence& seq) const; // Compare this sequence with another
// Friend for comparing Sequence objects
friend bool equals(const Sequence& seq1, const Sequence& seq2);
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;
}
// Comparison
/*
bool Sequence::equals(const Sequence& seq) const {
if (length != seq.length)
return false;
for (int i=0; i<length; i++)
if (pSequence[i] != seq.pSequence[i])
return false;
return true;
}
*/
bool equals(const Sequence& seq1, const Sequence& seq2) {
if (seq1.length != seq2.length)
return false;
for (int i=0; i<seq1.length; i++)
if (seq1.pSequence[i] != seq2.pSequence[i])
return false;
return true;
}
main.cpp
// main.cpp
//
#include <iostream>
#include <cstdlib>
#include <ctime>
using std::cout;
using std::endl;
#include "Sequence.h"
void main() {
const int nSeq = 5;
Sequence** pSequences = new Sequence*[nSeq];
pSequences[0] = new Sequence(5,6);
pSequences[1] = new Sequence(5,5);
pSequences[2] = new Sequence(5,6);
pSequences[3] = new Sequence(5,5);
pSequences[4] = new Sequence(4,8);
for (int i=0; i<4; i++)
for (int j=i+1; j<5; j++)
cout << endl
<< "sequences[" << i << "]"
//<< ((pSequences[i]->equals(*pSequences[j])) ? " is " : " is not ")
<< ((equals(*pSequences[i], *pSequences[j])) ? " is " : " is not ")
<< " equal to "
<< "sequences[" << j << "].";
cout << endl;
// 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
}