c++ - “const char *”类型的参数与“char”类型的参数不兼容
问题描述
我正在尝试使用指针和模板在 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’
编辑:我尝试使用dynamicIntArray<string> myarray;
这个时间它给出了分段错误。
解决方案
对于初学者,代码有几个错误。
例如,该函数size
返回一个无效值。
template <typename T>
int dynamicIntArray<T>::size(void)
{
return capacityIndex + 1;
}
最初,数组分配有 4 个元素
T *arrPtr = new T[4]();
int capacityIndex = 4;
但该函数返回 5 ( capacityIndex + 1
)。
在函数insert
中,可以访问分配的数组之外的内存。例如,capacityIndex - 1
在这个 if 语句中,当filledIndex 是 euql 到 then
if (filledIndex < capacityIndex)
{
arrPtr[++filledIndex] = n;
return true;
}
该值n
被写入等于的位置,capacityIndex
而索引的有效范围是[0, capacityIndex)
。
在此代码段中
capacityIndex *= 2;
T *newarrPtr = new T[capacityIndex]();
// Copy old array
for (int i = 0; i < capacityIndex; i++)
{
newarrPtr[i] = arrPtr[i];
}
数据成员 capacityIndex
增加了
capacityIndex *= 2;
但是,您在 for 循环中使用了这个新值
for (int i = 0; i < capacityIndex; i++)
{
newarrPtr[i] = arrPtr[i];
}
复制指向的数组中不存在的元素arrPtr
。
至于编译器错误,那么在这样的语句中
myarray.insert("A");
您正在使用字符串文字。例如,字符串文字"A"
具有const char[2]
在参数表达式中转换为类型的类型const char *
。
您尝试将此指针分配给类型char
为元素类型的已分配动态数组的对象的对象char
。
你应该这样写
myarray.insert( 'A' );
也就是说,您必须使用具有类型的字符文字而不是字符串文字char
- 类型模板参数的类型。
推荐阅读
- elasticsearch - 弹性搜索中多个字段的单词搜索
- c# - 如何在 IDictionary 中制作动态值
- android - 不支持 Android 11(R) 的 NDK 构建
- php - 如果在 WooCommerce 中满足条件,则尝试隐藏添加费用文本
- javascript - 使输入字段能够多次填写
- python - 如何使用 selenium python 登录谷歌账户
- r - 在前后观察变异虚拟变量
- angular - ng-select 在移动设备上具有更好的渲染效果
- java - 如何在原生 android 中嵌入多个统一模块?
- android - 尽管数据库中有值,但调试器在 Android Studio 中显示空值