提问人:Pasha 提问时间:11/28/2021 最后编辑:Pasha 更新时间:11/30/2021 访问量:82
如何实现从模板化类派生的类
How to implement class derived from templated class
问:
我有 2 个项目的解决方案。在第一个构建为库的项目中,我有模板化类
啊
#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() {}
};
然后是派生类
B.H.(英语:B.H)
#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()
{}
此代码生成为静态库 (.lib)。但是当我尝试在主项目中使用 B 类的实例时:
进程.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 ==========
答:
0赞
Minxin Yu - MSFT
11/30/2021
#1
LNK2019表示未添加相应的 lib 文件。您需要在 Properties>Linker>General>Additional Library Directory 中添加 Lib 文件目录,并在 Properties>Linker>Input>Additional Dependencies 中添加 Lib 文件。 请参考文档:在应用程序中使用静态库中的功能。
评论
process.cpp
process.obj
b.cpp
b.obj
#include "b.cpp"
b.cpp
process.cpp
b.cpp