在两个项目之间进行链接时,使用虚函数获取链接错误

时间:2014-04-22 17:47:31

标签: c++ inheritance virtual linker-errors

我在一个项目中创建了一个基类和派生类,比如称为ConsolApp1,其中基类有几个虚方法和一个虚析构函数。这些方法都设置为纯虚方法,然后在派生类中定义并使用override关键字覆盖。此外,派生类和基类都包含在命名空间中。当我创建一个新项目时,称为ConsolApp2并且与ConsolApp1位于相同的解决方案中,ConsolApp1实现派生类的对象,对于任何被声明为虚拟的方法或析构函数,都会出现链接错误。为了允许ConsolApp2包含派生类及其所在的命名空间,我不得不添加头文件位置的路径。我很确定我做的正确,因为当我尝试包含它时头文件显示出来。在此先感谢您的帮助。

这是我遇到的问题的一些伪代码。我能够编译没有错误的ConsolApp1,但ConsolApp2不构建并抛出三个链接错误,两个用于虚拟方法,一个用于虚拟析构函数。使用VS2012进行编译。错误是:

错误LNK2001:未解析的外部符号“public:virtual int const __thiscall FooSpace :: FooDerived :: GetSomething(void)const”(?GetSomething @ FooDerived @ FooSpace @@ UBE?BHXZ)

错误LNK2001:未解析的外部符号“public:virtual void __thiscall FooSpace :: FooDerived :: SetSomething(int)”(?SetSomething @ FooDerived @ FooSpace @@ UAEXH @ Z)

错误LNK2019:未解析的外部符号“public:virtual __thiscall FooSpace :: FooDerived :: ~FooDerived(void)”(?? 1FooDerived @ FooSpace @@ UAE @ XZ)在函数“public:virtual void * __thiscall FooSpace中引用: :FooDerived ::`标量删除析构函数'(unsigned int)“(?? _ GFooDerived @FooSpace @@ UAEPAXI @ Z)

ConsolApp1:

FooBase.h

namespace FooSpace
{
    class FooBase
    {
        public:
            FooBase(){}
            virtual ~FooBase() {}

            virtual const int GetSomething() const = 0;

            virtual void SetSomething(int f) = 0;
    };
}

FooDerived.h

#include "FooBase.h"

namespace FooSpace
{
    class FooDerived : FooBase
    {
        public:

            FooDerived() : FooBase(){}

            ~FooDerived() override;

            const int GetSomething() const override;

            void SetSomething(int f) override; 
    };
}

FooDerived.cpp

#include "FooDerived.h"

FooSpace::FooDerived::~FooDerived()
{
    //destruct an object of FooDerived
}

const int FooSpace::FooDerived::GetSomething() const
{
    int ret = 0;

    return ret;
}

void FooSpace::FooDerived::SetSomething(int f)
{
    // Set some private variable equal to f
}

FooMain.cpp - >包含以确保缺少main()

没有错误
#include "FooDerived.h"

using namespace FooSpace;

int main()
{

    FooDerived derivedObject;

    return 0;
}

ConsolApp2:

FooImplement.h

#include <FooDerived.h>
#include <vector>

using namespace std;
using namespace FooSpace;

class FooImpliment
{
    private:

        vector<FooDerived> fooVector;

    public:
        FooImpliment(void);
        ~FooImpliment(void);

        void SetFooVector(vector<FooDerived> newVector);

};

FooImplement.cpp

#include "FooImpliment.h"


FooImpliment::FooImpliment(void)
{
}


FooImpliment::~FooImpliment(void)
{
}

void FooImpliment::SetFooVector(vector<FooDerived> newVector)
{
    fooVector =  newVector;
}

ImplementMain.cpp - &gt;包含以消除缺少main()的错误

int main()
{
    return 0;
}

1 个答案:

答案 0 :(得分:0)

  

但ConsolApp2不编译并抛出三个链接错误。

错误,ConsolApp2.cpp 进行编译。问题不在于汇编,而是linking

在您的项目中,您应该编译

  • FooDerived.cpp
  • FooImplement.cpp
  • ImplementMain.cpp

如果不是,请将缺少的模块添加到项目中。

在这种情况下,似乎FooDerived.cpp没有被编译或不属于Visual Studio项目。