提问人: 提问时间:8/20/2020 最后编辑:Remy Lebeau 更新时间:8/20/2020 访问量:242
动态数组、指针和复制构造函数的问题
Issues with dynamic arrays, pointers and copy-constructors
问:
我在创建包含对象的动态数组时遇到了很多问题。
据我了解,因为我的数组正在处理对象,所以存储在数组中的类必须具有复制构造函数或赋值运算符,以便正确复制所有内容。
我已经成功地创建了这个程序,其中包含定义大小的正常数组。现在,我在使用动态数组创建相同的程序时遇到了很多问题。
第 1 类 要存储的对象:
class objToBeStored{
private:
string dataToBeStored;
int sizeOfArray;
string *storedArray;
public:
objToBeStored(); //empty constructor
objToBeStored& operator =(const objToBeStored& o); // assignment operator
~objToBeStored(); //destructor (no code inside);
bool getData(istream &stream);
//.....other methods to do stuff
};
objToBeStored::objToBeStored(){
//empty
}
objToBeStored& objToBeStored::operator=(const objToBeStored& o){
if(this != o){
dataToBeStored = o.dataToBeStored;
for (int i = 0; i < sizeOfArray; i++){
storedArray[i] = o.storedArray[i];
}
}
return *this;
}
void objToBeStored::getData(istream &stream){
stream >> dataToBeStored >> sizeOfArray;
storedArray = new string[sizeOfArray];
for(int i = 0; i < sizeOfArray; i++){
stream >> storedArray[i];
}
return !stream.eof();
}
//.....other methods to do stuff
类 2 包含存储上述对象的动态数组。一切都在工作,除了我如何声明我的动态数组和处理它的函数。因此,我将在下面编写以下代码:
class storageArrayClass{
private:
storageArrayClass *store;
storageArrayClass *storptr;
int numberOfstored;
public:
storageArrayClass(); //empty constructor
~storageArrayClass();
void addElm(objToBeStored & o);
//other functions to do stuff
};
storageArrayClass::storageArrayClass(){ //constructor
numberOfstored = 0;
}
storageArrayClass::~storageArrayClass(){
}
void storageArrayClass(istream &stream) {
objToBeStored o;
o.getData(stream);
if(numberOfstored == 0){ //check it this is the first element
store = new objToBeStored[1]; //create a new array with length 1
store[(numberOfstored] = o; //store object
}else{
objToBeStored tmpStore = new objToBeStored[(numberOfstored+1]; //create a temp. array with 1 more position
for(int i=0; i < numberOfstored; i++){
tmpStore[i] = store[i]; //copy original array to the temp. array
storptr = &tmpStore[i]; // increment a point
}
storptr++; //increment pointer to last position
*storptr = o; //store object in last position
delete[] store; //delete the original array
store = new objToBeStored[(numberOfstored+1]; //create a new original array
store = tmpStore;//copy temp. array
}
}
在出现以下错误之前,我设法将 3 个对象添加到我的动态数组中:
进程返回 -1073741819 (0xC0000005) 执行时间 : 5.059 s
请帮忙。我在这里阅读了无数的帖子,但我无法让它工作。
答: 暂无答案
评论
string *storedArray;
std::unique_ptr<string[]>
sizeOfArray
o.sizeOfArray
std::vector
objToBeStored
storageArrayClass
main
new[]
delete[]