"未解决的外部符号"尝试编译C ++项目时出错

时间:2015-07-29 08:25:08

标签: c++ templates

我正在尝试实现一些类,但在编译代码时遇到以下错误。我试图删除所有冗余代码,但没有一个有用。我不知道出了什么问题。

以下是编译代码时出现的错误:

Severity    Code    Description Project File    Line
Error   LNK2019 unresolved external symbol "public: __thiscall FullArray<int>::FullArray<int>(unsigned int)" (??0?$FullArray@H@@QAE@I@Z) referenced in function _wmain  FinancialDerivatives    C:\Users\Jeremy Nguyen\Documents\Visual Studio 2015\Projects\FinancialDerivatives\FinancialDerivatives\FinancialDerivatives.obj 1
Error   LNK1120 2 unresolved externals  FinancialDerivatives    C:\Users\Jeremy Nguyen\Documents\Visual Studio 2015\Projects\FinancialDerivatives\Debug\FinancialDerivatives.exe    1
Error   LNK2019 unresolved external symbol "public: virtual __thiscall FullArray<int>::~FullArray<int>(void)" (??1?$FullArray@H@@UAE@XZ) referenced in function _wmain  FinancialDerivatives    C:\Users\Jeremy Nguyen\Documents\Visual Studio 2015\Projects\FinancialDerivatives\FinancialDerivatives\FinancialDerivatives.obj 1

FullArray.h文件:

#pragma once
#include <vector>

template <class V>
class FullArray
{
private:
    std::vector<V> m_vector;        // Use STL vector class for storage

public:
    // Constructors & destructor
    FullArray();
    FullArray(size_t size);
    FullArray(const FullArray<V>& source);
    FullArray<V>& operator = (const FullArray<V>& source);
    virtual ~FullArray();
};

FullArray.cpp文件:

#include "stdafx.h"
#include "FullArray.h"


template<class V>
FullArray<V>::FullArray()
{
    m_vector = std::vector<V>(1);   // vector object with 1 element
}

template<class V>
FullArray<V>::FullArray(size_t size)
{
    m_vector = std::vector<V>(size);
}

template<class V>
FullArray<V>::FullArray(const FullArray<V>& source)
{
    m_vector = source.m_vector;
}

template<class V>
FullArray<V>& FullArray<V>::operator=(const FullArray<V>& source)
{
    // Exit if same object
    if (this == &source) return *this;

    // Call base class constructor
    //ArrayStructure<V>::operator = (source);

    // Copy the embedded vector
    m_vector = source.m_vector;

    return *this;
}

template<class V>
FullArray<V>::~FullArray()
{
}

主文件:

#include "stdafx.h"
#include "FullArray.h"

int _tmain(int argc, _TCHAR* argv[])
{
    FullArray<int> tmp(5);
    return 0;
}

1 个答案:

答案 0 :(得分:0)

如果编译模板,则源需要在使用它们的任何位置可用,因此请在.h文件底部包含.cpp文件,或者包含.cpp文件而不是.h文件。