如何改变指针?拷贝构造函数



我想设置"set"函数。这个函数将a2的值从"set(int x, int y)"";y"

#include <iostream>
using namespace std;
class IntArray {
private:
int* m_data;
int m_len;
public:
IntArray(int = 0, int = 0);
~IntArray();
void print(void);
IntArray(const IntArray& copy); // copy Constructor
void set(int x , int y) {
int temp = x;
x = y;
y = temp;//!!
}
};
IntArray::IntArray(int size, int init) {
if (size <= 0) {
m_data = nullptr; m_len = 0;
}
else {
m_data = new int[size];
m_len = size;
for (int idx = 0; idx < m_len; ++idx)
*(m_data + idx) = init;
}
}
IntArray::~IntArray() {
delete[]m_data;
}
void IntArray::print(void) {
for (int idx = 0; idx < m_len; ++idx)
cout << *(m_data + idx) << ' ';
cout << std::endl;
}
int main() {
cout << "a1: ";
IntArray a1{ 10, 100 };
a1.print();
cout << "a2: ";
IntArray a2{ a1 };// 10~100
a2.set(3, 999);
a2.set(9, 123);
a2.print();
return 0;
}

除外

a1: 100 100 100 100 100 100 100 100 100 100 100 100 100 100
a2: 100 100 100 100 999 100 100 100 100 100 100 123

这是你需要的。

让我们修正你的声明,并引入两个新的助手方法,alloccopyFromOther

class IntArray {
private:
int* m_data;
int m_len;
void alloc(int len);
void copyFromOther(const IntArray& copy);
public:
IntArray();
IntArray(const IntArray& copy);
~IntArray();
IntArray& operator=(const IntArray& copy);
void print();
void set(int index, int value);
};

辅助方法用于快速分配和复制。注意,我没有对length == 0进行特殊处理。那是因为说new int[0]是完全可以的。它将分配一个长度为0的指针。如果您想在长度为零时强制使用空指针,则可以更改此设置。还要注意,复制构造函数需要能够处理"对自己的复制"。也就是说,如果你输入:

IntArray arr(10, 20);
arr.set(5,5);
arr = arr;

上面的看起来很奇怪,当复制构造函数不能处理这种情况时,它是许多错误的根源。

现在实现了

void IntArray::alloc(int len) {
delete [] m_data; // erase what we had before
m_data = new int[len]; // you could say m_data = len ? new int[len] : nullptr
m_len = len;
}
void IntArray::copyFromOther(const IntArray& copy) {
// special case - allow for "copying to ourselves" by doing nothing
// if we didn't handle this, the alloc function would delete the pointer
if (copy.m_data == m_data) {
return;
}
alloc(copy.m_len);
for (int idx = 0; idx < m_len; ++idx)
m_data[idx] = copy.m_data[idx];
}
}

然后实现

IntArray::IntArray() : m_data(nullptr) {
alloc(0);
}
IntArray::IntArray(const IntArray& copy) m_data(nullptr), m_len(0) {
copyFromOther(copy);
}
IntArray& IntArray::operator=(const IntArray& copy) {
copyFromOther(copy);
return *this;
}

让我们修复你的set方法,因为你在一个单独的问题中问过它:

void IntArray::set(int index, int value) {
if ((index >= 0) && (index < m_len)) {
m_data[index] = value;
}
}

你的析构函数和打印方法都很好。print不需要显式的void参数。

最新更新