[英]C++ Dynamic Array Template issue
我仍然是學校的初學者程序員,因此被分配了此問題:
“制作自己的動態數組模板。它應該允許創建連續的數組(填充相同類型的東西),您可以擴展這些數組而不必擔心空間不足。
使用malloc和free做一個版本。
使用new和delete做一個版本。”
到目前為止,這就是我所擁有的:
#include <iostream>
#include <sstream>
#include "Array.h"
using namespace std;
int main(){
Array<int> *testArray = new Array<int>(5);
testArray->initArray();
testArray->printArray();
testArray->addData(7);
testArray->printArray();
return 0;
}
這是“ Array.h”文件:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
template<typename T>
class Array{
public:
Array(int size){
size = size;
data = new T[size];
};
Array<T> *addData(T dataToAdd){
Array <T> *tmp = new Array <T> (this->size);
tmp->data = this->data;
Array <T> *newData = new Array<T> (this->size + 1);
for (int i = 0; i < this->size + 1; ++i){
if (i < this->size){
//newData->data[i] = tmp->data[i];
newData->setData(tmp->getData()[i], i);
}
else{
//newData->data[i] = dataToAdd;
newData->setData(dataToAdd, i);
}
}
return newData;
};
void initArray(){
for (int i = 0; i < this->size; ++i){
//this->data[i] = i;
this->setData(i, i);
}
};
void printArray(){
ostringstream oss;
string answer = "";
for (int i = 0; i < this->size; ++i){
oss << this->data[i] + " ";
//cout << this->data[i] << " ";
}
answer = oss.str();
cout << answer << "asdf" << endl;
};
T* getData(){
return this->data;
}
int getSize(){
return this->size;
}
void setData(T data, int index){
this->getData()[index] = data;
}
private:
int size;
T* data;
};
到目前為止,應該在我的主文件中發生的是應該有一個由5個int組成的數組,這些數組已從initArray函數初始化為0、1、2、3、4。
然后,它應該打印出顯示“ 0 1 2 3 4”的數組,並添加另一個“ 7”,然后打印出顯示“ 0 1 2 3 4 7”的新數組。
出於某種原因,我認為這與在兩個文件之間移動時丟失數據有關,我的Array類的“數據”字段未正確更改。
我什至在主程序上對此進行了硬編碼,在其中我使用setData函數編寫了一個for循環,該函數將Array初始化為“ 0 1 2 3 4”,然后使用另一個for循環手動打印出這些值,但輸出僅為0 0 0 00。”
現在,如代碼所示,輸出為:
asdf
asdf
由於之前是輸出空格,因此我添加了“ asdf”,以查看我的printArray是否可以正常工作。
總結一下,為什么我的私有字段“數據”中的數據沒有正確存儲? 我對使用C ++編程非常陌生,任何建議將不勝感激。 謝謝您的寶貴時間,如果有任何您不了解的內容,請澄清一下,我會盡力而為。
編輯:問題解決了! 謝謝大家的幫助,問題出在我的構造函數以及我如何在main中調用函數。
一個問題是您的構造函數:
Array(int size){
size = size;
data = new T[size];
};
擁有它的方式只是將您的size參數分配給它自己,這沒有任何效果。 解決該問題的一種方法是對參數使用不同的名稱:
Array(int size_arg){
size = size_arg;
data = new T[size_arg];
};
但是,首選方法是使用構造函數初始化器語法:
Array(int size) : size(size), data(new T[size]) {};
使用構造函數初始化器語法,編譯器知道您正在嘗試初始化特定成員,並且不會在參數名稱和成員名稱之間造成混淆。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.