待解决new int(i*j)

时间:2023-03-09 18:10:15
待解决new int(i*j)

这里的确应该用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(,);
    int i,j;
    ;i < ; ++i )
        ; j < ; j ++ )
            a[i][j] = i *  + j;
    ;i < ; ++i ) {
        ; j < ; j ++ ) {
            cout << a(i,j) << ",";
        }
        cout << endl;
    }
    cout << "next" << endl;
    Array2 b;     b = a;
    ;i < ; ++i ) {
        ; j < ; j ++ ) {
            cout << b[i][j] << ",";
        }
        cout << endl;
    }
    ;
}