我正在尝试使用指针和模板在C ++中实现动态数组实现,以便我可以接受所有类型。该代码在int
上工作正常,但是在使用char
时会出错。我在网上尝试了其他SO问题,但未发现与我有关的情况。代码:
#include <iostream>
#include <string>
using namespace std;
template <typename T>
class dynamicIntArray
{
private:
T *arrPtr = new T[4]();
int filledIndex = -1;
int capacityIndex = 4;
public:
// Get the size of array
int size(void);
// Check if array is empty
bool isEmpty(void);
// Insert a data to array
bool insert(T n);
// Show the array
bool show(void);
};
template <typename T>
int dynamicIntArray<T>::size(void)
{
return capacityIndex + 1;
}
template <typename T>
bool dynamicIntArray<T>::insert(T n)
{
if (filledIndex < capacityIndex)
{
arrPtr[++filledIndex] = n;
return true;
}
else if (filledIndex == capacityIndex)
{
// Create new array of double size
capacityIndex *= 2;
T *newarrPtr = new T[capacityIndex]();
// Copy old array
for (int i = 0; i < capacityIndex; i++)
{
newarrPtr[i] = arrPtr[i];
}
// Add new data
newarrPtr[++filledIndex] = n;
arrPtr = newarrPtr;
return true;
}
else
{
cout << "ERROR";
}
return false;
}
template <typename T>
bool dynamicIntArray<T>::show(void)
{
cout << "Array elements are: ";
for (int i = 0; i <= filledIndex; i++)
{
cout << arrPtr[i] << " ";
}
cout << endl;
return true;
}
int main()
{
dynamicIntArray<char> myarray;
myarray.insert("A");
myarray.insert("Z");
myarray.insert("F");
myarray.insert("B");
myarray.insert("K");
myarray.insert("C");
cout << "Size of my array is: " << myarray.size() << endl;
myarray.show();
}
错误:
invalid conversion from ‘const char*’ to ‘char’
myarray.insert("A");
…"A"
是const char[]
,但插入期望char
。您可以将其更改为myarray.insert('A')