使用继承时未解析的引用

时间:2010-11-23 15:35:15

标签: c++ templates visual-c++ inheritance linker-errors

如何将模板定义转换为单独的头文件?

我的代码在包含在单个main.cpp中时编译。

maip.cpp

#include <windows.h>
#include <tchar.h>

template<class T1, class T2>
class Base {
public:
    virtual ~Base() {}
    virtual T1 f1();
    virtual T2 f2();
};

template<class T1, class T2>
T1 Base<T1, T2>::f1() {return T1();}
template<class T1, class T2>
T2 Base<T1, T2>::f2() {return T2();}

class Derived : public Base<int, int> {
public:
    virtual ~Derived() {}
};

int _tmain(int argc, _TCHAR* argv[])
{
    int i;
    Derived d;
    i = d.f1();
    return 0;
}

然而,当我分手时,我得到了未解析的外部符号:

的main.cpp

#include <windows.h>
#include <tchar.h>

#include "Base.h"
#include "Derived.h"

int _tmain(int argc, _TCHAR* argv[])
{
    int i;
    Derived d;
    i = d.f1();
    return 0;
}

Base.h

#pragma once

template<class T1, class T2>
class Base {
public:
    Base();
    virtual ~Base() {}
    virtual T1 f1();
    virtual T2 f2();
};

template<class T1, class T2>
T1 Base<T1, T2>::f1() {return T1();}
template<class T1, class T2>
T2 Base<T1, T2>::f2() {return T2();}

Derived.h

#pragma once

class Derived : public Base<int, int> {
public:
    virtual ~Derived() {}
};

这导致:

  

错误1错误LNK2019:未解决   外部符号“public:__ thiscall   基地:: Base的(空)”   (?? 0?$ Base @ HH @@ QAE @ XZ)参考   功能“public:__ thiscall   衍生::派生(无效)”   (?? 0Derived @@ @ QAE XZ)

1 个答案:

答案 0 :(得分:5)

您没有为Base的构造函数提供实现。尝试添加

template<class T1, class T2>
Base<T1, T2>::Base () { }

或者,您可以从第二个代码段中删除其声明。 (它的第一个代码示例中也没有。)

你的链接器基本上说Derived::Derived ()试图调用你明确声明的Base::Base (),但他找不到它的实现。