简体   繁体   English

模板中的虚拟 function 继承 class

[英]virtual function in template inherited class

I am new to templates and I have searched the web for this error but I don't know how to fix it it.我是模板新手,我已经在 web 中搜索了这个错误,但我不知道如何修复它。 Already checked Why can templates only be implemented in the header file?已经查过了为什么模板只能在header文件中实现?

State.h State.h

template <class entityType>
class State
{
public:
    State() = default;
    virtual void Enter(entityType * owner);

};

EnterMine.h EnterMine.h

#include "State.h"

class Miner;
class EnterMine : public State<Miner>
{
public:
    EnterMine() = default;
    virtual void Enter(Miner *) {

    };
};

and Miner.cpp is blank Miner.cpp 为空白

and the problem appears in main.cpp问题出现在 main.cpp

#include "EnterMine.h"

int main()
{
    EnterMine a;
}

The error I get is a linking error:我得到的错误是链接错误:

LNK2001 unresolved external symbol "public: virtual void __thiscall State::Enter(class Miner *)" (?Enter@?$State@VMiner@@@@UAEXPAVMiner@@@Z) LNK2001 无法解析的外部符号“public: virtual void __thiscall State::Enter(class Miner *)”(?Enter@?$State@VMiner@@@@UAEXPAVMiner@@@Z)

(Note: this answer was written for the original question, it has been completely rewritten after that.) (注意:此答案是为原始问题编写的,之后已完全重写。)

Every function that is declared and used, should be defined somewhere.每个声明和使用的 function 都应该在某个地方定义。

It seems that you declare EnterMine::EnterMine() but never define it.似乎您声明EnterMine::EnterMine()但从未定义它。 If this constructor does nothing, either omit it (it will be implicitly defined by a compiler ), or mark it as = default;如果此构造函数什么都不做,要么省略它(它将由编译器隐式定义),要么将其标记为= default; . .

class EnterMine : public State<Miner>
{
public:
    EnterMine() = default;
    ...
};

This also applies to the State::State() constructor.这也适用于State::State()构造函数。

Even though it's a singleton, you're still calling the constructor.即使它是 singleton,您仍在调用构造函数。 Thus, you will still need to define the constructor.因此,您仍然需要定义构造函数。

In fact, you need to define every function you declare in your header.实际上,您需要定义您在 header 中声明的每个 function。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM