1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
|
#include <iostream>
using namespace std;
#define NUM 10
class A
{
int v[NUM];
public:
A() { }
A(int x[]) {
for (int i = 0; i<NUM; i++)
v[i] = x[i];
}
// (1) operator: [ index ], which returns v[index]
int& operator[](int i){
static int err = -1;
if (i < 0 || i > NUM - 1)
return err;
else
return this->v[i];
}
// (2) operator: +, which adds the corresponding array elements
A operator+(const A& rhs)
{
A temp;
for (int i = 0; i < NUM; i++)
{
temp.v[i] = this->v[i] + rhs.v[i];
}
return temp;
}
// (3) operator: *, which multiplies the corresponding array Elements
A operator*(const A& rhs)
{
A temp;
for (int i = 0; i < NUM; i++)
{
temp.v[i] = this->v[i]*rhs.v[i];
}
return temp;
}
// (4) operator: ++, which adds each array element by 1
A& operator++() {
for (int i = 0; i < NUM; i++)
this->v[i] += 1;
return *this;
}
A operator++(int) {
A tmp(*this);
operator++();
return tmp;
}
// (5) operator: =, which assigns all the array elements from one object to another
A& operator=(const A& rhs)
{
if (this != &rhs){
for (int i = 0; i < NUM; i++)
this->v[i] = rhs.v[i];
}
return *this;
}
//Operator <<
friend ostream &operator<<(ostream& out, const A& thing){
for (int i = 0; i < NUM; i++)
out << thing.v[i] << ' ';
return out;
}
};
int main()
{
int x[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
A b1(x), b2, b3, b4, b5;
cout << "b1[5]: " << b1[5] << endl;
b2 = b1;
cout << "b1: ";
cout << b1;
cout << "\nb2: ";
cout << b2;
b3 = b1 + b2;
cout << "\nb3: ";
cout << b3;
b4 = b1*b2;
cout << "\nb4: ";
cout << b4;
b5 = b4;
++b5;
cout << "\nb5: ";
cout << b5 << endl;
}
|