我正在尝试编写一个具有一些功能的模板/类,但我遇到了一个看起来相当新手的问题。我有一个简单的插入函数和一个显示值函数,但是每当我尝试显示值时,我总是收到看起来像内存地址的东西(但我不知道),但我想接收存储的值(在这个具体示例,int 2)。我不确定如何将其取消引用为一个值,或者我是否完全搞砸了。我知道 vector 是更好的选择,但是我需要在此实现中使用数组 - 老实说,我想更透彻地了解代码和正在发生的事情。对于如何完成此任务的任何帮助,我们将不胜感激。
示例输出(每次都以相同的方式运行程序): 003358C0
001A58C0
007158C0
代码:
#include <iostream>
using namespace std;
template <typename Comparable>
class Collection
{
public: Collection() {
currentSize = 0;
count = 0;
}
Comparable * values;
int currentSize; // internal counter for the number of elements stored
void insert(Comparable value) {
currentSize++;
// temparray below is used as a way to increase the size of the
// values array each time the insert function is called
Comparable * temparray = new Comparable[currentSize];
memcpy(temparray,values,sizeof values);
// Not sure if the commented section below is necessary,
// but either way it doesn't run the way I intended
temparray[currentSize/* * (sizeof Comparable) */] = value;
values = temparray;
}
void displayValues() {
for (int i = 0; i < currentSize; i++) {
cout << values[i] << endl;
}
}
};
int main()
{
Collection<int> test;
int inserter = 2;
test.insert(inserter);
test.displayValues();
cin.get();
return 0;
}
最佳答案
好吧,如果你坚持,你可以编写和调试自己的限制版本std::vector
.
首先,不要memcpy
来自未初始化的指针。设置values
至 new Comparable[0]
在构造函数中。
第二,memcpy
正确的字节数:(currentSize-1)*sizeof(Comparable)
.
三、不要memcpy
根本。假设 Comparable
类型都可以逐字节复制,这是 C++ 中的一个严重限制。相反:
编辑:更改uninitialized_copy
至 copy
:
std::copy(values, values + currentSize - 1, temparray);
第四,删除不再使用的旧数组:
delete [] values;
第五,除非代码要插入很少,否则将数组扩展不止一个。 std::vector
通常将其大小增加 1.5 倍。
第六,不要自增currentSize
直到大小改变。这将改变所有这些 currentSize-1
进入currentSize
,这就不那么烦人了。 <g>
七、大小为N
的数组索引来自 0
至 N-1
, 因此新数组的顶部元素位于 currentSize - 1
, 不是 currentSize
.
第八,我有没有提到,你真的应该使用std::vector
.
关于c++ - 模板中的数组和指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12354216/