c++ - 复制构造函数 Big 3 C++ 问题

标签 c++ arrays operator-overloading destructor copy-constructor

我正在努力实现三大理念(赋值运算符重载、复制构造函数、析构函数)。我下面的代码会使程序崩溃。它编译所以我什至看不到任何错误提示。请帮忙。

enter code here

#include <iostream>
using namespace std;
#include <string>
#include <fstream>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <vector>
#include <windows.h>
#include <cstring>
#include <cctype>
#include <iomanip>
#include <algorithm>
#include<sstream>


class TwoD
{
private:
int MaxRows;
int MaxCols;
double** outerArray;

public:
TwoD(int maxRows, int maxCols)
{
    MaxRows = maxRows;
    MaxCols = maxCols;
    outerArray = new double *[MaxRows];
    for (int i = 0; i < MaxRows; i++)
        outerArray[i] = new double[MaxCols];
}

TwoD(const TwoD& rightside)
{
    for (int l = 0; l < MaxRows; l++)  
        for (int m = 0; m < MaxCols; m++)
            outerArray[l][m] = rightside.outerArray[l][m];    
}

void input()
{
    for (int k = 0; k < MaxRows; k++)
        for (int j = 0; j < MaxCols; j++)
            cin >> outerArray[k][j];
}

void outPut()
{
    for (int l = 0; l < MaxRows; l++)
    {
        for (int m = 0; m < MaxCols; m++)
            cout << outerArray[l][m] << " ";
        cout << endl;
    }
}

const TwoD& operator =(const TwoD& rightSide)
{
    for (int l = 0; l < MaxRows; l++)
    {
        for (int m = 0; m < MaxCols; m++)
            outerArray[l][m] = rightSide.outerArray[l][m];
        cout << endl;
    }

    return *this;
}



const TwoD operator + (const TwoD& rightSide)
{
    for (int l = 0; l < MaxRows; l++)
    {
        for (int m = 0; m < MaxCols; m++)
            outerArray[l][m] = outerArray[l][m] + rightSide.outerArray[l][m];
        cout << endl;
    }

    return *this;
}

~TwoD()
{
    for (int i = 0; i < MaxRows; i++)
        delete[] outerArray[i];
    delete[] outerArray;
}

};

int main()
{
TwoD example1(3, 3), example2(3,3), example3(3,3);
cout << "input example1" << endl;
example1.input();
example1.outPut();

cout << "input example2" << endl;
example2.input();
example2.outPut();

cout << "combining the two is" << endl;
example3 = example1 + example2;
example3.outPut();


return 0;
}

修改了拷贝构造函数

TwoD(const TwoD& rightside): MaxRows(rightside.MaxRows), MaxCols(rightside.MaxCols)
{
    outerArray = new double *[MaxRows];
    for (int i = 0; i < MaxRows; i++)
        outerArray[i] = new double[MaxCols];

    for (int l = 0; l < MaxRows; l++)  
        for (int m = 0; m < MaxCols; m++)
            outerArray[l][m] = rightside.outerArray[l][m];    
}

最佳答案

  1. 您的复制构造函数无法为矩阵分配内存。
  2. 您的复制赋值运算符和 operator+() 未能说明 *thisrightSide 具有不同维度的可能性。

关于c++ - 复制构造函数 Big 3 C++ 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18738504/

相关文章:

C++ 运算符重载 Int 类型

c++ - 枚举警告 : outside the range

c++ - 让我的 GTK 应用程序在 Linux 上启动时启动

C++ 重载 `-`

C++ 显式声明在默认构造函数中触发警告

javascript - 使用 JavaScript 从数组中删除零值

arrays - 了解用于对数组中的元素求平方的大 O

arrays - 将函数拆分为数组。类型不匹配错误#13

c# - 我应该重载 == 运算符吗?

c++ - 我应该如何正确重载使用 friend 的运算符?