#include <iostream> using namespace std; int g_ret = -1000; class Array { public: Array(int size) :_size(size) { m_data = new int[size]; } ~Array() { delete []m_data; m_data = NULL; } Array (const Array& other) //拷贝构造函数 { this->_size = other._size; this->m_data = new int[other._size]; memcpy(this->m_data,other.m_data,other._size*sizeof(int)); } Array& operator = (const Array& o) //复制运算符重载 { if(o == *this) //先判断一下是否一样,要是一样的话 就不用赋值了 return *this; else { delete []this->m_data; this->_size = o._size; this->m_data = o.m_data; memcpy(this->m_data,o.m_data,o._size*sizeof(int)); return *this; } } int & operator[] (int index) { if(this->_size > index && index >= 0) { return this->m_data[index]; }else{ cout<<"error"<<endl; return g_ret; } } friend bool operator != (const Array&a1,const Array& a2); friend bool operator == (const Array&a1,const Array& a2); friend istream& operator >>(istream& in, Array& arr); friend ostream& operator <<(ostream& out,const Array& arr); private: int _size; int *m_data; }; bool operator == (const Array&a1, const Array& a2) { if(a1._size == a2._size) //先判断一下要赋值的两个是否相同 { for(int i=0; i<a1._size; i++) { if(a1.m_data[i] != a2.m_data[i]) //判断一下 两个类的 m_data 成员是否相同 return false; } return true; } else return true; } bool operator != (const Array &a1,const Array & a2) { return !(a1 == a2); } istream& operator >>(istream& in, Array& arr) { for(int i=0; i< arr._size; ++i) { in>>arr[i]; } return in; } ostream& operator <<(ostream& out,const Array& arr) { for(int i = 0; i < arr._size; ++i) { out<<arr.m_data[i]<<" "; } out<<endl; return out; } int main() { Array a(5); cin>>a; cout<<a; return 0; }
留个脚印
评论测试
评论测试456
评论测试123