我试图为我所有的实验室工作建立一个“框架”,但后来我遇到了一个令人沮丧的链接器错误,处理纯虚函数的实现。
当我从 .cpp 文件(如 returntype classname::function() {.....} )定义纯虚函数时,出现链接器错误,告诉我未提供纯虚函数的定义。 .
但是,当我简单地将定义放到头文件中时,它运行良好.. 我知道我听起来很混乱......但是下面的代码肯定会帮助您了解正在发生的事情..
谁能帮我理解为什么会这样?
该项目包含4个文件,(2个头文件和2个cpp文件)
1 > 框架.h:
#ifndef _FRAMEWORK
#define _FRAMEWORK
#include<iostream>
class labTest
{
public :
virtual void execute() = 0;
};
#endif
=======================================
2 >堆栈数组.h:
#include "FrameWork.h"
#include<iostream>
using namespace std;
template <class T>
class Stack_Array : public labTest
{
public:
virtual void execute();
};
=======================================
3 > Stack_Array.cpp:
#include "Stack_Array.h"
template<class T>
virtual void Stack_Array<T>::execute(void) // I beleive i am defining the pure virtual function here, but my compiler ll not agree.
{
std::cout << "Test";
}
=======================================
4 > Main_Run.cpp:
#include<istream>
#include"FrameWork.h"
#include"Stack_Array.h"
#include<vector>
using namespace std;
void main()
{
vector<labTest*> list(5);
vector<labTest*>::iterator it;
it = list.begin();
Stack_Array<int>* sa = new Stack_Array<int>();
list.insert(it,sa);
list[0]->execute();
getchar();
}
==========================================
构建输出:
1>------ Rebuild All started: Project: Lab FrameWork, Configuration: Debug Win32 ------
1>Build started 11/20/2012 6:16:48 PM.
1>InitializeBuildStatus:
1> Touching "Debug\Lab FrameWork.unsuccessfulbuild".
1>ClCompile:
1> Stack_Array.cpp
1> Main_Run.cpp
1> Generating Code...
1>Main_Run.obj : error LNK2001: unresolved external symbol "public: virtual void __thiscall Stack_Array<int>::execute(void)" (?execute@?$Stack_Array@H@@UAEXXZ)
1>C:\Users\BSP-4\Documents\Visual Studio 2010\Projects\SFML\Lab FrameWork\Debug\Lab FrameWork.exe : fatal error LNK1120: 1 unresolved externals
1>
1>Build FAILED.
1>
1>Time Elapsed 00:00:01.64
========== Rebuild All: 0 succeeded, 1 failed, 0 skipped =======================
如果我制作我的 Stack_Array.h 它会起作用:
#include "FrameWork.h"
#include<iostream>
using namespace std;
template <class T>
class Stack_Array : public labTest
{
public:
void execute() // give the definition here instead of Stack_Array.cpp and it will work !
{
cout << "Test Success !!";
}
};
我确信这是一些愚蠢的事情..我是否忽略了什么?..但我仍然需要帮助....
提前致谢...