我一直在尝试创建一个适用于我的程序的复制构造函数,但是,当我运行我的代码时,它总是给我一个错误:
1.) "member 'lengthOfArray' was not initialized in this constructor"
2.) "member 'lengthOfArray' was not initialized in this constructor"
现在我明白了上面两个错误是怎么回事,但是我不明白的两个错误是这两个:
3.) previous definition is here
4.) redefinition of 'copy'
这是我目前拥有的:
simpleVector(const simpleVector& copy) {
simpleVector cy;
simpleVector copy(cy);
}
现在我要实现的指令是:
您自己的复制构造函数执行深层复制,即创建一个动态数组并从作为参数传递给复制构造函数的另一个数组复制元素。
我以前从未创建过复制构造函数,他们也没有在类里面介绍过它,所以我不确定具体如何实现它,但我搜索了很多资源但运气不佳。在复制构造函数中使用 for 循环是否很典型?对于我做错的任何帮助,我们将不胜感激。我的整个代码:
#include <iostream>
using namespace std;
// simpleVector template
template<class Temp>
class simpleVector {
// private members
private:
Temp* tempPointer;
int lengthOfArray;
public:
// default no-arg constructor
simpleVector() {
tempPointer = NULL;
lengthOfArray = 0;
}
// single argument constructor
simpleVector(int dynamicArray) {
lengthOfArray = dynamicArray;
tempPointer = new Temp[lengthOfArray];
}
// Copy constructor
simpleVector(const simpleVector& copy) {
simpleVector cy;
simpleVector copy(cy);
}
};
最佳答案
simpleVector(const simpleVector& copy) { // copy decleared here
simpleVector cy;
simpleVector copy(cy); // Being defined here again.
}
这就是编译器所提示的。
你需要这样的东西:
simpleVector(const simpleVector& copy) : lengthOfArray(copy.lengthOfArray),
tempPointer(new int[copy.lengthOfArray])
{
// Add code to copy the data from copy.tempPointer to this->tempPointer.
}
关于c++ - 为简单 vector 实现复制构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33675412/