我正在使用動態陣列的模板類,并且我的代碼已成功編譯,但是我對動態陣列中給定元素的 get 函式似乎不起作用。每當我輸出函式時似乎什么都沒有輸出,但這沒有意義,因為我的 size 函式作業正常,并且表明陣列中確實有東西,我無法輸出它。任何人都可以幫忙嗎?
#include <iostream>
using namespace std;
template <class T>
class Wrapper{
private:
T* array;
int size;
public:
Wrapper(){
array = NULL;
size = 0;
}
int returnSize(){
return size;
}
void addEntry(string input){
if(returnSize()==0){
array = new string[returnSize() 1];
array[returnSize()] = input;
size =1;
}
else{
T* newArray = new T[returnSize() 1];
for(int i = 0; i<returnSize(); i ){
newArray[i] = array[i];
}
newArray[returnSize()] = input;
size =1;
string *array = new string[returnSize()];
array = newArray;
}
}
bool deleteEntry(string input){
int mySize = returnSize();
string* testArray = new string[mySize];
for(int i = 0; i<mySize; i ){
if(array[i]==input){
return true;
break;
}
}
string*newArray = new string[mySize-1];
for(int i = 0; i<mySize; i ){
if(array[i]!=input){
newArray[i =1] = array[i];
}
}
delete[]array;
array = newArray;
return true;
}
string getEntry(int input){
if(input>size){
return NULL;
}
return this->array[input];
}
void operator=(const Wrapper w){
this->size = w.returnSize();
string *newArray = new string[size];
for(int i = 0; i<size; i ){
newArray[i] = w.getEntry(i);
}
this->array = newArray;
}
~Wrapper(){
delete[] array;
}
};
int main(){
Wrapper<string> w;
w.addEntry("sam");
w.addEntry("Josh");
w.addEntry("tom");
cout<<"Here"<<endl;
cout<<w.returnSize();
for(int i = 0; i<<w.returnSize(); i ){
cout<<w.getEntry(i);
}
}
uj5u.com熱心網友回復:
只是為了收集調查結果,如果您從以下位置洗掉此行addEntry:
string *array = new string[returnSize()];
并將您的最終 for 回圈更改為:
for(int i = 0; i < w.returnSize(); i ){
cout<<w.getEntry(i)<<"\n";
}
那么這正是你所期望的。我自己運行過。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/473689.html
