如何使用模板类C++
How to use a template class C++
我在使用用C++编写的类时遇到问题。我最近刚开始学习C++,我很快就找到了正确的方法,但在用"正确"的方法学习之后,我还是犯了一个错误。。。。因此,如果这只是一些愚蠢的误解,我提前道歉(尽管我对此表示怀疑…)相关代码低于
ArrayList.h
#ifndef ARRAYLIST_H_
#define ARRAYLIST_H_
#include <string>
template<class T>
class ArrayList {
private:
//Data fields-------------------//
T *array;
int size;
int capacity;
bool sorted;
//Methods-----------------------//
void reallocate();
void reallocate(int newSize);
T* mergeSort(T* array, int arraySize);
public:
//Constructors------------------//
ArrayList();
ArrayList(int theSize);
//Methods-----------------------//
//Operations
bool add(T element);
bool add(T element, int index);
bool add(ArrayList<T> list);
bool add(ArrayList<T> list, int index);
std:string toString();
};
#endif /* ARRAYLIST_H_ */
ArrayList.cpp
#include "ArrayList.h"
//~Constructors-----------------------------------------------
/**
* Default constructor,
* creates a 20 element ArrayList, of type T.
*/
template<class T>
ArrayList<T>::ArrayList() {
array = new T[20];
capacity = 20;
size = 0;
}
//~Methods---------------------------------------------------
/**
* Adds the passed in element to the end of the ArrayList.
*
* Runs in O(n) in worst case, where reallocate is called.
*
* @param element the element to add to the array.
*/
template<class T>
bool ArrayList<T>::add(T element) {
bool value = false;
if (element != NULL) {
if ((size - 1) == capacity) {
value = reallocate();
}
if (value) {
array[size] = element;
size++;
}
}
return value;
}
ArrayListTest.cpp
#include "ArrayList.h"
#include <iostream>
int main(void) {
using namespace std;
ArrayList<int> myList();
myList.add(184387);
myList.add(14);
myList.add(147);
myList.add(1);
myList.add(-37);
myList.add(584);
myList.add(-2147);
myList.add(0);
myList.add(-75);
myList.add(147);
myList.add(-37);
myList.add(0);
myList.add(25);
myList.add(187);
myList.add(92);
myList.add(-17);
cout << myList.toString();
}
错误出现在TestArrayList.cpp文件中。我在所有的add调用和cout调用上都有一个错误。
添加调用的错误为:
request for member 'add' in 'myList', which is of non-class type 'ArrayList<int>()'
cout调用上的错误是:
Method 'toString' could not be resolved
有人知道我在这里做错了什么吗?
ArrayList<int> myList();
应该是
ArrayList<int> myList;
您正在运行最令人烦恼的解析(用谷歌搜索)。基本上,ArrayList<int> myList();
不声明变量,而是声明一个名为myList
的函数,该函数不接受参数并返回一个ArrayList<int>
。
一些旁注:
- 你在构造函数中分配内存,但从来没有释放它。你应该有一个析构函数
- 这意味着你应该遵守三条规则(谷歌)
- 我的通灵能力(是的,我有,保持低调)告诉我,你的下一个问题是它没有联系将实现移动到标头。模板必须具有对所有专门化它们的翻译单元可见的实现
相关文章:
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- C++:TypeDef使用元组
- 使用std::multimap迭代器创建std::list
- 从不同线程使用int64的不同字节安全吗
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 为什么在全局范围内使用"extern int a"似乎不行?
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 如何使用Google Mock来模拟gettimeofday()
- 如何使用默认参数等选择模板专业化
- 为什么使用 "this" 指针调用派生成员函数?
- 使用新行和不使用新行读取文件
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 如何确定我已使用非编码文件到达 EOF?
- 如何在cuSparse中使用cusparseXcoo2csr从coo转换为csc
- 使用CMake创建QML插件
- 使用 LLVM 的 libc++ 时,__1 符号从何而来?
- 在std::cout之后使用std::cin时,换行符从何而来
- 为什么以及在何处在C++中使用引用和指针
- 基例如何影响使用递归函数的哪些行