首页 文章

使用继承时未解析的引用

提问于
浏览
2

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

我的代码在包含在单个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 :: Base(void)”(?? 0?$ Base @HH @@ QAE @ XZ)在函数“public:__thiscall Derived :: Derived(void)”中引用“(?? 0Derived @@ QAE @ XZ)

1 回答

  • 5

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

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

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

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

相关问题