您好,我收到以下错误:
Error 9 error LNK1120: 2 unresolved externals
Error 8 error LNK2019: unresolved external symbol "public: virtual __thiscall physics::~physics(void)" (??1physics@@UAE@XZ) referenced in function "public: virtual void * __thiscall physics::`scalar deleting destructor'(unsigned int)" (??_Gphysics@@UAEPAXI@Z)
Error 7 error LNK2019: unresolved external symbol "public: virtual __thiscall student::~student(void)" (??1student@@UAE@XZ) referenced in function __unwindfunclet$??0physics@@QAE@XZ$0
使用以下代码发生:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class student{
protected:
string fName,sName;
int id;
vector<string> cname;
vector<int> cmark;
public:
virtual ~student();
virtual void addCourse(string name, int mark)=0;
};
class physics : public student{
public:
physics(){//Initialize default values
fName="blank";
sName="blank";
id=0;
cname.push_back("none");
cmark.push_back(0);
};
~physics();
void addCourse(string name, int mark){
if(cname.size()==1){//override default value for a size of 1
cname[0]=name;
cmark[0]=mark;
}
else{
cname.push_back(name);
cmark.push_back(mark);
}
}
};
上面的编译很好,但是当我尝试使用以下方法在 main() 中初始化一个对象时:
int main(){
//Database Storage
vector<student*> DB;
DB.push_back(new physics);
}
那是我收到错误的时候(删除 push_back 行修复它,但我的程序需要它)。我做错了什么?
最佳答案
Turns out adding braces to the end of the destructors fixed it. What difference does that make? (from the comments)
区别在于,在一种情况下,您的声明缺少定义;在第二种情况下,您提供一个(空的)内联定义。
尝试调用已声明但未定义的函数(如第一种情况)会导致链接器引发未解析的引用错误 - 毕竟,当函数调用时它应该做什么找到了一个实现不可用的函数?
关于c++ - 使用多态性时 Unresolved external 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16385923/