gpt4 book ai didi

c++ - 重载 = 动态数组 C++ 类中的运算符

转载 作者:行者123 更新时间:2023-11-30 00:35:33 26 4
gpt4 key购买 nike

我一直在尝试添加两个二维数组。在我为“=”添加重载函数后,C++ 开始崩溃一次。编译器崩溃了。但是没有添加

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

并禁用重载运算符成员函数,一切正常。
你能帮忙吗?

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];
}

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;
}

最佳答案

The compiler just crashes.

真的吗?对我来说,该程序可以编译,但由于双重删除而在运行时崩溃。

Could you please help?

要使类正确可复制:

  • 根据 Rule of Three,您需要复制构造函数和复制赋值运算符。 .您只有赋值运算符。
  • 赋值运算符应该返回一个引用,而不是一个拷贝。

一个合适的复制构造函数可能看起来像

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

(如果您不能使用 C++11 的委托(delegate)构造函数,那么您将需要复制默认构造函数的初始化,或者将其移出到两个构造函数都调用的单独函数中)。

有了复制构造函数后,您可以考虑使用 copy-and-swap idiom获得对异常更友好的赋值运算符。在 C++11 中,您还可以考虑使类可移动(通过复制指向目标的指针,并使受害者中的指针无效),以避免在某些情况下进行不必要的内存分配。

另外,operator+ 不应该修改它的参数;它应该返回一个新创建的对象。您的实现更适合 operator+=(尽管像 operator= 一样,它应该返回一个引用,而不是一个拷贝)。

一旦您了解了手动内存管理的工作原理,您应该使用标准容器和智能指针等类来为您解决所有这些繁琐的问题。特别地,std::vector 是一个动态数组。

关于c++ - 重载 = 动态数组 C++ 类中的运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18696487/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com