我有下面的類友誼和運算符重載幫助
#ifndef Container_H
#define Container_H
#include <iostream>
using namespace std;
class Container{
friend bool operator==(const Container &rhs,const Container &lhs);
public:
void display(ostream & out) const;
private:
int sizeC; // size of Container
int capacityC; // capacity of dynamic array
int * elements; // pntr to dynamic array
};
ostream & operator<< (ostream & out, const Container & aCont);
#endif
這個源文件
#include "container.h"
/*----------------------------*********************************************
note: to test whether capacityC and sizeC are equal, must i add 1 to sizeC?
seeing as sizeC starts off with 0??
*/
Container::Container(int maxCapacity){
capacityC = maxCapacity;
elements = new int [capacityC];
sizeC = 0;
}
Container::~Container(){
delete [] elements;
}
Container::Container(const Container & origCont){
//copy constructor?
int i = 0;
for (i = 0; i<capacityC; i++){ //capacity to be used here?
(*this).elements[i] = origCont.elements[i];
}
}
bool Container::empty() const{
if (sizeC == 0){
return true;
}else{
return false;
}
}
void Container::insert(int item, int index){
if (sizeC == capacityC){
cout << "\n*** Next: Bye!\n";
return; // ? have return here?
}
if ((index >= 0) && (index <= capacityC)){
elements[index] = item;
sizeC++;
}
if ((index < 0) && (index > capacityC)){
cout<<"*** Illegal location to insert--"<< index << ". Container unchanged. ***\n";
}//error here not valid? according to original a3? have i implemented wrong?
}
void Container::erase(int index){
if ((index >= 0) && (index <= capacityC)){ //correct here? legal location?
int i = 0;
while (i<capacityC){ //correct?
elements[index] = elements[index+1]; //check if index increases here.
i++;
}
sizeC=sizeC-1; //correct? updated sizeC?
}else{
cout<<"*** Illegal location to be removed--"<< index << ". Container unchanged. ***\n";
}
}
int Container::size()const{
return sizeC; //correct?
}
/*
bool Container::operator==(const Container &rhs,const Container &lhs){
int equal = 0, i = 0;
for (i = 0; i < capacityC ; i++){
if (rhs.elements[i] == lhs.elements[i]){
equal++;
}
}
if (equal == sizeC){
return true;
}else{
return false;
}
}
ostream & operator<< (ostream & out, const Container & aCont){
int i = 0;
for (i = 0; i<sizeC; i++){
out<< aCont.elements[i] << " " << endl;
}
}
*/
我沒有在頭文件(只是一個quikie)的其他功能。無論如何,「/ * * /」中的最後兩個函數無法工作,我在這裏做錯了什麼?
所述第一功能是將看到兩個數組是否彼此相等