重载左右位移符号用于iostream。

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
#include<iostream>

using std::cout;
using std::cin;

class Vector {
public :
explicit Vector(int size = 1) {
this->len = size;
v = new int[size];
}

~Vector() {
delete v;
}

int &operator[](int i);

friend std::ostream &operator<<(std::ostream &, Vector &); //declare friend

friend std::istream &operator>>(std::istream &, Vector &);

private :
int *v;
int len;
};

std::ostream &operator<<(std::ostream &output, Vector &ve) {
int *i = ve.v;
while (i < ve.v + ve.len) {
output << *i;
i++;
}
return output;
}

std::istream &operator>>(std::istream &input, Vector &ve) {
int *i = ve.v;
while (i < ve.v + ve.len) {
input >> *i;
i++;
}
return input;
}

int &Vector::operator[](int i) {
return *(this->v + i);
}

int main() {
int k;
cout << "Input the length of Vector A :\n";
cin >> k;
Vector A(k);
cout << "Input the elements of Vector A :\n";
cin >> A;
cout << "Output the elements of Vector A :\n";
cout << A;
}

使用友元函数使得全局函数operator<</>>可以访问私有成员变量。