推 fjf1980:謝謝! 再去研究看看! 03/31 12:25
#include <iostream>
using namespace std;
class Array
{
int size;
int *data;
public:
Array(int s)
{
size=(s>0?s:10);
data=new int[size];
}
virtual ~Array()
{
delete[] data;
}
Array(const Array& other)
{
int i;
this->size = other.size;
this->data = new int[this->size];
for(i=0; i<this->size; ++i)
{
this->data[i] = other.data[i];
}
}
Array& operator=(const Array &right)
{
int i;
for(i=0;i<this->size;i++)
{
this->data[i]=right.data[i];
}
return *this;
}
const Array operator+(const Array &op2) const
{
Array result(this->size);
int i;
for(i=0;i<size;i++)
{
result.data[i]=this->data[i]+op2.data[i];
}
return result;
}
const Array operator*(int k) const
{
Array result(this->size);
int i;
for(int i=0;i<size;i++)
{
result.data[i]=this->data[i]*k;
}
return result;
}
friend istream& operator>>(istream&, Array&);
friend ostream& operator<<(ostream&, const Array&);
};
ostream& operator<<(ostream& out, const Array& a)
{
int i;
int size_1 = a.size-1;
for(i=0; i<size_1; ++i)
{
out << a.data[i] << " ";
}
out << a.data[i];
return out;
}
istream& operator>>(istream& in, Array& a)
{
int i;
for(i=0; i<a.size; ++i)
{
in >> a.data[i];
}
return in;
}
int main(int argc, char *argv[])
{
Array X(10);
Array Y(10);
Array Z(10);
cout << "Input array x:";
cin >> X;
cout << "Input array y:";
cin >> Y;
Z=(X+Y)*2;
cout << "Array z:";
cout << Z << endl;
return EXIT_SUCCESS;
}
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 114.44.19.112