Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/162.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 简写为c++;代码,我想是';这是由于类的解构功能。但是我找不到_C++ - Fatal编程技术网

C++ 简写为c++;代码,我想是';这是由于类的解构功能。但是我找不到

C++ 简写为c++;代码,我想是';这是由于类的解构功能。但是我找不到,c++,C++,我认为这个bug与delete动态数组操作有关。但我不确定细节 我现在正在学习C++,所以我是个新手。这是一本书中的小练习,我正在尝试解决它。“main()”函数部分是它最初的样子,因此我只允许编写关于类“Array2”的代码 提前谢谢 #include <iostream> #include <cstring> using namespace std; class Array2 { int row, col;

我认为这个bug与delete动态数组操作有关。但我不确定细节

我现在正在学习C++,所以我是个新手。这是一本书中的小练习,我正在尝试解决它。“main()”函数部分是它最初的样子,因此我只允许编写关于类“Array2”的代码

提前谢谢

    #include <iostream>
    #include <cstring>
    using namespace std;
    class Array2
    {
        int row, col;
        int **a;
    public:
        Array2(int s1=1, int s2=1) 
        {
            row = s1;
            col = s2;
            a = new int *[row];
            for (int i = 0; i < row; i++)
            {
                a[i] = new int[col];
            }
        };
        Array2(Array2 & b)
        {
            a = b.a;
        }
        ~Array2()
        {
            for (int i = 0; i < row; i++)
            {   
                    delete[] a[i];
            }

            delete[] a;
        }
        int * operator [] (int i)
        {
            return a[i];
        }
        int operator () (int s1, int s2)
        {
            return a[s1][s2];
        }

    };
    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;
    }**
#包括
#包括
使用名称空间std;
类数组2
{
int row,col;
国际**a;
公众:
数组2(整数s1=1,整数s2=1)
{
行=s1;
col=s2;
a=新整数*[行];
对于(int i=0;icout您的复制构造函数不正确。您不能只复制内部存储器的地址,否则最终会释放它两次。

问题在于此代码段中的赋值

Array2 b; b = a;
          ^^^^^
您没有定义复制赋值运算符。因此编译器以与您错误定义复制构造函数类似的方式隐式定义它

    Array2(Array2 & b)
    {
        a = b.a;
    }
您必须在构造期间使用复制构造函数或在赋值期间使用复制赋值操作符对对象进行深度复制


否则,多个指针指向同一内存,该内存将被删除至少两次。

您的复制构造函数是错误的。它会导致同一内存被多次
delete
d。这也是我第一次看到有人将析构函数称为解构函数,但听起来很酷。