【问题标题】:How to implement class derived from templated class如何实现从模板类派生的类
【发布时间】:2022-01-05 05:39:30
【问题描述】:

我有里面有 2 个项目的解决方案。在作为库构建的第一个项目中,我有模板类

啊.h

#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

#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 类的实例时:

process.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 ==========

【问题讨论】:

  • 看来这里的问题只是关于如何编译多个文件;模板与问题无关。显然有一个名为process.cpp 的文件被编译为生成process.obj,并且在您显示的输出中没有提到b.cppb.obj。您之前是否成功编写过涉及多个源文件的项目? (注意:不要在任何地方#include "b.cpp";这不是正确的解决方案)
  • 我只是展示示例,因为我无法附加整个项目。但是,如果我在没有 b.cpp 的头类中实现 B 类,那么一切都可以。
  • 您尚未将b.cpp 添加到您的项目中。它没有被编译,或者至少没有链接。
  • 您需要提供更多详细信息。您的项目包含(至少)两个源文件,process.cppb.cpp。错误消息看起来像是在说只有其中一个被链接。如果是这样,那么问题出在项目的设置上,而不是代码上。
  • 它存在并编译。 a.h、b.h 和 b.cpp 存在于解决方案中的单独项目中并编译为库。但在 process.cpp 我使用那个 B 类。

标签: c++ visual-studio class templates linker-errors


【解决方案1】:

LNK2019表示没有添加对应的lib文件。您需要在Properties>Linker>General>Additional Library Directories中添加Lib文件目录,并在Properties>Linker>Input>Additional Dependencies中添加Lib文件。 请参考文档:Use the functionality from the static library in the app

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-09
    • 2016-02-17
    • 2015-04-10
    • 2017-01-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多