标签:pre 指针 this opera 赋值 不能 clu main ret
这里的确应该用new int [i*j] 来申请一片空间,但new int(i)的含义就像是给p指针指向的内容赋值了,相当于只申请了一个4个字节。
问题是,为什么后面b不能输出结果呢?
#include <iostream> #include <cstring> using namespace std; class Array2 { public: int * p; int r; int c; Array2(){p = NULL;}; Array2(int i,int j){ r = i; c = j; p = new int(i*j); // p = new int [i*j]; } Array2 & operator=(const Array2 & a) { if( p ) delete [] p; r = a.r; c = a.c;p = new int [r * c]; memcpy( p, a.p, sizeof(int ) * r * c); return * this; } int * operator[](int i){ return p + i*c; } int & operator()(int i,int j){ return *(p + i*c + j); } }; int main() { Array2 a(3,4); int i,j; for( i = 0;i < 3; ++i ) for( j = 0; j < 4; j ++ ) a[i][j] = i * 4 + j; for( i = 0;i < 3; ++i ) { for( j = 0; j < 4; j ++ ) { cout << a(i,j) << ","; } cout << endl; } cout << "next" << endl; Array2 b; b = a; for( i = 0;i < 3; ++i ) { for( j = 0; j < 4; j ++ ) { cout << b[i][j] << ","; } cout << endl; } return 0; }
标签:pre 指针 this opera 赋值 不能 clu main ret
原文地址:https://www.cnblogs.com/fanmu/p/10605585.html