如何使用模板类C++

How to use a template class C++

本文关键字:C++ 何使用      更新时间:2023-10-16

我在使用用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>

一些旁注:

  • 你在构造函数中分配内存,但从来没有释放它。你应该有一个析构函数
  • 这意味着你应该遵守三条规则(谷歌)
  • 我的通灵能力(是的,我有,保持低调)告诉我,你的下一个问题是它没有联系将实现移动到标头。模板必须具有对所有专门化它们的翻译单元可见的实现