#include <iostream> #include <string> #include <cassert> #include <memory> using namespace std; class My { public: My() { n = 0; arr = NULL; cout<<"调用无参构造函数"<<endl; } My(int _n) { n = _n; arr = new int[n]; for (int i=0; i<n; i++) { arr[i] = i + 1; } cout<<"调用有参数构造函数"<<endl; } //复制构造函数 My(const My &my)//注意该函数的参数必需是引用类型的,不然后有无穷多的复制构造函数的调用,而产生无限循环 { n = my.n; arr= new int[n]; memcpy(arr, my.arr, n*sizeof(int)); cout<<"调用复制构造函数"<<endl; } //赋值运算符 My& operator = (const My &my) { if (this == &my) { return *this; } delete []arr; n = my.n; arr = new int[n]; cout<<"调用赋值运算符"<<endl; return *this; } //重载[]运算符,注意返回值要返回"引用" int& operator[] (int i) { if (i>=0 && i<=n) { return arr[i]; } } ~My() { cout<<"调用析构函数"<<endl; } private: int n; int *arr; }; int main() { My a(10); My b = a;//调用复制构造函数 My c; c = a;//调用赋值运算符 for (int i=0; i<10; i++) { cout<<b[i]<<" "; } cout<<endl; }