【发布时间】:2020-09-16 07:49:28
【问题描述】:
我正在尝试使用动态数组。当我尝试重载“=”运算符时,它不起作用。在调试文件时,它不会执行 void 函数来重载运算符。
#include <iostream>
using namespace std;
class cppArray {
public:
cppArray(int size);
~cppArray();
int read(int index);
void write(int content, int index);
void operator=(cppArray& s);
int search(int target);
int size();
private:
int* myArray;
int arraySize;
};
cppArray::cppArray(int size) {
myArray = new int[size];
arraySize = size;
}
//delete the memory space assigned to myArray
cppArray::~cppArray() {
delete[] myArray;
myArray = 0;
}
int cppArray::read(int index) {
if (index < arraySize) {
return myArray[index];
}
else {
cout << "Out of range" << endl;
exit(1);
}
}
这里我尝试将原始数组的内容复制到辅助数组中,然后重新定义原始数组的大小,以便可以向原始数组添加更多内容
void cppArray::write(int content, int index) {
if (index < arraySize) {
myArray[index] = content;
}
else {
cppArray auxArray(arraySize);
auxArray.myArray = myArray;
delete[] myArray;
arraySize = index + 1;
myArray = new int[arraySize];
myArray = auxArray.myArray;
myArray[index] = content;
}
}
我很确定这是错误的,但我无法找到正确重载它的方法
void cppArray::operator=(cppArray& s) {
delete[] s.myArray;
s.myArray = new int[arraySize];
for (int i = 0; i < arraySize; i++)
{
myArray[i] = s.myArray[i];
}
}
int cppArray::size() {
return arraySize;
}
int main(int argc, char** argv) {
cppArray dsArray(3);
dsArray.write(1, 0);
dsArray.write(2, 1);
dsArray.write(3, 2);
dsArray.write(4, 3);
for (int i = 0; i < dsArray.size(); i++) {
cout << dsArray.read(i) << "\t";
}
cout << endl;
return 0;
}```
【问题讨论】:
-
请提供minimal reproducible example,强调“最小”。我没有找到你在代码中调用
operator= -
你为什么不直接使用std::vector?
-
另外,一个合适的rule of three 的三脚凳似乎也缺少一条腿(即copy-ctor)。而且我认为您应该花一些时间阅读What are the basic rules/idioms of operator overloading,特别是关于赋值运算符的部分,因为您的结果类型错误,并且可以说是错误的参数类型。
-
实现
operator=的一种快速简便的方法是使用Copy and Swap Idiom。它还具有在编程中尽可能接近万无一失的优势。 -
auxArray.myArray = myArray;只复制一个指针。你delete它指向的内存,使auxArray.myArray无效。然后你分配一些新的内存,只是立即用你保存的无效指针替换指向它的指针。
标签: c++ class operator-overloading overloading dynamic-arrays