Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // there is some bugs with += and = operators
- //Array.h
- #pragma once
- class Array
- {
- public:
- Array(const Array &);
- ~Array();
- Array(int= 10); // defult size of array
- int GetSize()const;
- void Print() const;
- int find(const int) const;
- Array& operator=(const Array&);
- bool operator==(const Array&)const;
- Array& operator+=(const Array& a);
- int& operator[](int);
- operator int() { return numofElements; }
- private:
- int numofElements;
- int *p;
- };
- //Array.cpp
- #include "Array.h"
- #include <assert.h>
- #include <iostream>
- #include <iomanip>
- using namespace std;
- Array::Array(const Array & n) //copy cons
- {
- this->numofElements = n.numofElements;
- this->p = new int[numofElements];
- assert(p);
- for (int i = 0; i < numofElements; i++)
- {
- this->p[i] = n.p[i];
- }
- }
- Array::~Array()
- {
- delete [] p;
- assert(p);
- p = NULL;
- }
- Array::Array(int size)
- {
- numofElements = size;
- p = new int[size];
- assert(p);
- for (int i = 0; i < size; i++)
- {
- p[i] = 0; //calloc
- }
- }
- int Array::GetSize() const
- {
- return this->numofElements;
- }
- void Array::Print() const
- {
- for (int i = 0; i < numofElements; i++)
- {
- cout << setw(3) << p[i];
- }
- cout << endl;
- }
- int Array::find(const int x) const
- {
- for (int i = 0; i < numofElements; i++)
- {
- if (p[i]==x)
- {
- return 1;
- }
- return -1;
- }
- }
- Array & Array::operator=(const Array& n) // a3=a4
- {
- if (this->numofElements!=n.numofElements)
- {
- delete[] p;
- p = NULL;
- p = new int[n.numofElements];
- assert(p);
- }
- for (int i = 0; i < numofElements; i++)
- {
- p[i] = n.p[i];
- }
- return *this; //return ptr to the "array"
- }
- bool Array::operator==(const Array &n)const //
- {
- if (this->numofElements != n.numofElements)
- {
- return false;
- }
- else
- {
- for (int i = 0; i < numofElements; ++i)
- {
- if (p[i]!=n.p[i])
- {
- return false;
- }
- return true;
- }
- }
- }
- Array& Array::operator+=(const Array& a)
- {
- Array temp = *this;
- delete[]p;
- p = new int[numofElements + a.numofElements];
- assert(p);
- for (int i = 0; i < numofElements; i++)
- p[i] = temp.p[i];
- for (int i = 0; i < numofElements+a.numofElements; i++)
- p[i] = a.p[i - numofElements];
- numofElements = numofElements + a.numofElements;
- return *this;
- }
- int& Array::operator[](const int n)
- {
- return p[n];
- }
- //Main.cpp
- #include <iostream>
- #include "Array.h"
- using namespace std;
- void main()
- {
- Array a1;
- Array a2(5);
- a2.GetSize();
- a1.Print();
- a2.Print();
- for (int i = 0; i < a1.GetSize(); i++)
- {
- a1[i] = i+1;
- }
- a1.Print();
- Array a3(50);
- a3.Print();
- a1.find(5);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement