未解析的外部符号1和b/w虚与纯虚的区别

Unresolved external symbol 1 and the difference b/w virtual and pure virtual?

本文关键字:区别 外部 符号      更新时间:2023-10-16

这可能出了什么问题?我们在哪里用纯virtual func() = 0; ?此外,在一个virtual命令下是否可以使用不同的功能?我的意思是,像rotate,我可以写成move()吗?努力掌握多态性。

using namespace std;
class shape
{
public:
    virtual void rotate();
};
class triangle : public shape
{
public:
    void rotate()
    {
        cout << "in triangle";
    }
};
class line : public shape
{
public:
    void rotate()
    {
        cout << "in line";
    }
};
class circle : public shape
{
public:
    void rotate()
    {
        cout << "in circle";
    }
};
int main()
{
    shape s;
    triangle t;
    circle c;
    line l;
    shape* ptr;
    ptr = &s;
    ptr->rotate();
    ptr = &t;
    ptr->rotate();
    ptr = &l;
    ptr->rotate();
    system("PAUSE");
    return 0;
}
error: LNK 1120: 1 unresolved externals   
error: LNK 2001: unresolved external symbol "public: virtual void_thiscall shape::rotate(void)"(?rotate@shape@@UAEXXZ)

如果你想使用"cout",你必须包含<iostream>头文件。

虚纯函数是一个接口,因此如果不在派生类中实现派生类,就不能实例化派生类。

必须在基类

中实现rotate函数

#include <iostream>
using namespace std;
class shape
{
public:
virtual void rotate()
{
   cout << "in shape";
}
};
class triangle:public shape
{
public:
void rotate()
{
    cout << "in triangle";
}
};
class line : public shape
{
public:
void rotate()
{
    cout << "in line";
}

};
class circle : public shape
{
public:
void rotate()
{
    cout << "in circle";
}
};
int main()
{
shape s;
triangle t;
circle c;
line l;
shape *ptr;
ptr = &s;
ptr->rotate();
ptr = &t;
ptr->rotate();
ptr = &l;
ptr->rotate();
system("PAUSE");
return 0;
}

由于您将shape::rotate方法声明为虚方法而不是纯虚方法,因此链接器正在寻找shape::rotate的实现。

存在两种解:
1)通过附加= 0,使shape::rotate a 为纯虚函数。2)创建空的shape::rotate函数。

在Shape声明中,使用如下:

virtual void rotate() = 0;