[c++]インスタンス-クラスarray、リロードオペレータ

7749 ワード


#include "ARRAY.hpp"
#include <iostream>
#include <cstdlib>
#include <iomanip>
using namespace std;
ARRAY::ARRAY(int arraysize) {
    size = (arraysize > 0 ? arraysize : 10);
    ptr = new int[size];
    for (int i = 0; i < size; i++) {
        ptr[i] = 0;
    }
}

ARRAY::ARRAY(const ARRAY &arraytocopy)
: size (arraytocopy.size) {
    ptr = new int[size];
    for (int i = 0; i < size; i++) {
        ptr[i] = arraytocopy.ptr[i];
    }
}

ARRAY::~ARRAY() {
    delete [] ptr;
}

int ARRAY::getsize() const {
    return size;
}

const ARRAY &ARRAY::operator = (const ARRAY &right) {
    if (&right != this) {
        if (size != right.size) {
            delete [] ptr;
            size = right.size;
            ptr = new int[size];
        }
        for (int i = 0; i < size; i++) {
            ptr[i] = right.ptr[i];
        }
    }
    return *this;
}

bool ARRAY::operator==(const ARRAY &right) const {
    if (size != right.size) {
        return false;
    }
    for (int i = 0; i < size; i++) {
        if (ptr[i] != right.ptr[i]) {
            return false;
        }
    }
    return true;
}

int &ARRAY::operator[](int subscript) {
    if (subscript < 0 || subscript >= size) {
        cout << "
ERROR"
<< subscript << "out_of_range" <<endl; exit(1); } return ptr[subscript]; } int ARRAY::operator[](int subscript) const { if (subscript < 0 || subscript >= size) { cout << "
ERROR"
<< subscript << "out_of_range" <<endl; exit(1); } return ptr[subscript]; } istream &operator >> (istream &input, ARRAY &a) { for (int i = 0; i < a.size; i++) { input >> a.ptr[i]; } return input; } ostream &operator << (ostream &output, const ARRAY &a) { int i; for (i = 0; i < a.size; i++) { output << setw(12) << a.ptr[i]; // setw() if (( i + 1) % 4 == 0) { output << "
"
; } } if (i % 4 != 0) { output << endl; } return output; }
#ifndef ARRAY_hpp
#define ARRAY_hpp

#include <iostream>
using namespace std;

class ARRAY {
    friend ostream &operator << (ostream&, const ARRAY &);
    friend istream &operator >> (istream&, ARRAY &);
public:
    ARRAY(int = 10);
    ARRAY(const ARRAY &);
    ~ARRAY();
    int getsize() const;
    const ARRAY &operator = (const ARRAY &);
    bool operator == (const ARRAY &) const;
    bool operator != (const ARRAY &right) const {
        return ! (*this == right);
    }
    int &operator [](int);
    int operator [](int) const;

private:
    int size;
    int *ptr;
};

#endif /* ARRAY_hpp */