【问题标题】:Having an error in c++; Unimplemented constructors?c++ 中出现错误;未实现的构造函数?
【发布时间】:2014-03-12 22:17:54
【问题描述】:

我是编程新手,我正在尝试实现一个简单版本的 ArrayList。我遇到了一个错误,当我试图找到解决方案时,人们说这是因为声明了构造函数但未实现。我实现了我在标题中声明的所有构造函数,所以我不确定出了什么问题。一些建议表示赞赏!

错误 1 ​​错误 LNK2019: 无法解析的外部符号 "public: __thiscall ArrayList::ArrayList(void)" (??0?$ArrayList@H@@QAE@XZ) 在函数_main中引用

错误 2 错误 LNK2019: 无法解析的外部符号 "public: void __thiscall ArrayList::add(int)" (?add@?$ArrayList@H@@QAEXH@Z) 在函数_main中引用

错误 3 error LNK1120: 2 unresolved externals

ArrayList.h

#pragma once
#ifndef ArrayList_h
#define ArrayList_h
#include <stdexcept>
using namespace std;

template <class T>
class ArrayList
{
public:
    ArrayList();
    ~ArrayList();
    void add(T item);
    void expandArray();
    T get(int index);

private:
    int size;
    int length;
    T* list;
};

#endif

//ArrayList.cpp
#include "ArrayList.h"

template <class T>
ArrayList<T>::ArrayList(){
    size=1;
    length=0;
    list = new T(size);
    for(int x=0; x<size;x++){
        list[x]=NULL;
    }

}

template <class T>
ArrayList<T>::~ArrayList(){
    delete[] list;
}


template <class T>
void ArrayList<T>::add(T item){
    if(length>=size){
        expandArray();
    }
    list[length]=item;
    length++;
}

template <class T>
void ArrayList<T>::expandArray(){
    size*=2;
    T* temp = new T(size);
    for(int x=0;x<size;x++){
        temp[x]=NULL;
    }
    for(int x=0;x<length;x++){
        temp[x]=list[x];
    }
    delete[] list;
    list=temp;
}

template <class T>
T ArrayList<T>::get(int index){
    if(index>length||index<0){
        throw out_of_range("Index out of bounds!");
    }
    return list[index];
}

Main.cpp

#include "ArrayList.h"


int main(){

    ArrayList<int>* list = new ArrayList<int>();

    for(int x=0; x<=30;x++){
        list->add(x);
    }

    return 0;
}

【问题讨论】:

    标签: c++


    【解决方案1】:

    模板定义需要在头文件中。将您的 ArrayList&lt;T&gt;::ArrayList 构造函数定义移动到 ArrayList.h。

    【讨论】:

    • 对不起,我对 c++ 和标头还比较陌生。我是否只是将 ArrayList::ArrayList 的整个实现移到标题中?我认为标题应该只用于声明。
    • @user3272701 整个模板类需要在标题中。对于非模板类,您是正确的。
    • ...或使用显式模板实例化,但我认为这只会混淆整个情况,所以我要坐在角落里吃点馅饼。
    • 非常感谢,我现在明白了。
    猜你喜欢
    • 2018-03-07
    • 2012-08-24
    • 1970-01-01
    • 1970-01-01
    • 2013-02-23
    • 1970-01-01
    • 2016-05-19
    • 2017-08-31
    • 2017-12-25
    相关资源
    最近更新 更多