- class A {
- public: A() : _n(0),
- _p(NULL) {}
- explicit A(int n) : _n(n),
- _p(new int[n]) {} //把数组的基地址赋值给_p
- A(int n, int * p) : _n(n),
- _p(p) {}
- //如果省略以下语句,编译器自动生成以下两条语句(浅拷贝)
- A(const A & that) : _n(that._n),
- _p(that._p) {} //浅拷贝
- A & operator = (const A & that) {
- _n = that._n,
- _p = that._p;
- return * this;
- }
- virtual~A() {
- if (_p) {
- delete[] _p;
- _p = NULL;
- }
- }
- public: int & operator[](int i);
- const int & operator[](int i) const;
- private: int _n;
- int * _p;
- };
- int & A: :operator[](int i) {
- if (i < 0 || i >= 4) throw std: :out_of_range("Out of range when trying to access the object... ");
- return _p[i];
- }
- const int & A: :operator[](int i) const {
- if (i < 0 || i >= 4) throw std: :out_of_range("Out of range when trying to access the object..");
- return _p[i];
- }
- int main() {
- A a(4),
- b;
- for (int i = 0; i < 4; i++) {
- a[i] = i + 1;
- }
- std: :cout << "Before object assignment:" << std: :endl;
- for (int i = 0; i < 4; i++) {
- std: :cout << a[i] << " ";
- }
- std: :cout << std: :endl;
- b = a;
- std: :cout << "After object assignment:" << std: :endl;
- for (int i = 0; i < 4; i++) {
- std: :cout << b[i] << " ";
- }
- std: :cout << std: :endl;
- return 0; //程序结束时,系统崩溃
- }
来源: