簡體   English   中英

如何實現從模板化 class 派生的 class

[英]How to implement class derived from templated class

我有里面有 2 個項目的解決方案。 在作為庫構建的第一個項目中,我模板化了 class

#pragma once

#include <memory>

template<class MessageType, class HandlerType>
class A
{
    std::unique_ptr<MessageType> msg;
    std::unique_ptr<HandlerType> handler;
public:
    A() : msg(std::make_unique<MessageType>()), handler(std::make_unique<HandlerType>()) {}
    virtual ~A() {}
};

然后導出class

bh

#include "a.h"
#include <string>

struct MyMessage
{};
struct MyHandler
{};
class B : A<MyMessage, MyHandler>
{
    std::string name;
public:
    B(const std::string& str);
    virtual ~B();
};

並實施

b.cpp

#include "b.h"

B::B(const std::string& str)
{
}

B::~B()
{}

此代碼構建為 static 庫 (.lib)。 但是當我嘗試在主項目中使用 B class 的實例時:

進程.cpp

#include <iostream>
#include "b.h"

int main()
{
    std::cout << "Hello World!\n";
    B opa("yes");
}

編譯器無法鏈接

Rebuild started...
1>------ Rebuild All started: Project: ConsoleApplication3, Configuration: Debug Win32 ------
1>b.cpp
1>ConsoleApplication3.cpp
1>Generating Code...
1>ConsoleApplication3.vcxproj -> C:\Users\user\source\repos\tmpClass\Debug\ConsoleApplication3.lib
2>------ Rebuild All started: Project: tmpClass, Configuration: Debug Win32 ------
2>process.cpp
2>process.obj : error LNK2019: unresolved external symbol "public: __thiscall B::B(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const &)" (??0B@@QAE@ABV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@Z) referenced in function _main
2>process.obj : error LNK2019: unresolved external symbol "public: virtual __thiscall B::~B(void)" (??1B@@UAE@XZ) referenced in function _main
2>C:\Users\user\source\repos\tmpClass\Debug\tmpClass.exe : fatal error LNK1120: 2 unresolved externals
2>Done building project "tmpClass.vcxproj" -- FAILED.
========== Rebuild All: 1 succeeded, 1 failed, 0 skipped ==========

LNK2019 表示沒有添加對應的lib文件。 您需要在Properties>Linker>General>Additional Library Directories中添加 Lib 文件目錄,並在Properties>Linker>Input>Additional Dependencies中添加 Lib 文件。 請參考文檔: 在應用程序中使用 static 庫中的功能

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM