“Error: Unresolved external symbol” whenever I use

2019-02-15 09:01发布

I feel like I'm doing something incredibly stupid, but I simply can't figure out what's wrong with my code. I even made a super simplified version of the code and the error still occurs:

#include <iostream>

using namespace std;

class c1{
public:
    c1(){}
    ~c1(){}

    virtual int add(int a, int b);

private:
protected:


};

class c2 : c1{
public:
    c2(){}
    ~c2(){}

    int add(int a, int b){
        return a+b;
    }

};

int main(){

    c2 c;
    c.add(5,6);

}

Can anyone spot what I'm sure is the silliest error of all time?

Here's the exact error message:

1>main.obj : error LNK2001: unresolved external symbol "public: virtual int __thiscall c1::add(int,int)" (?add@c1@@UAEHHH@Z)

6条回答
我只想做你的唯一
2楼-- · 2019-02-15 09:41

c1.add is not pure virtual, you must add = 0.

virtual int add(int a, int b) = 0; 
查看更多
冷血范
3楼-- · 2019-02-15 09:42
virtual int add(int a, int b);

This is not a declaration of a pure virtual function. It's just a declaration of a virtual function. It lacks a definition, which is why you get the error.

virtual int add(int a, int b) = 0;

This is a declaration of a pure virtual function. It does not require a definition, which is why won't get the error.

查看更多
Ridiculous、
4楼-- · 2019-02-15 09:42

virtual int add(int a, int b); This means "my function add can be subclassed". In other to be "my function add can be subclassed and is pure virtual" you need

virtual int add(int a, int b) = 0;
查看更多
\"骚年 ilove
5楼-- · 2019-02-15 09:46

change virtual int add(int a, int b); to virtual int add(int a, int b) = 0;

查看更多
闹够了就滚
6楼-- · 2019-02-15 10:04

c1::add() is not pure virtual, it's just not implemented. This means the linker is correct to look for a body, and correct to complain when it can't find one. You probably meant this:

class c1{
public:
    c1(){}
    ~c1(){}

    virtual int add(int a, int b) = 0;  // adding = 0 makes the function pure virtual

private:
protected:


};
查看更多
Evening l夕情丶
7楼-- · 2019-02-15 10:06

You are getting linker error, because c1::add(int,int) is not implemented. either make it pure virtual or implement it.

查看更多
登录 后发表回答