这可能会出现什么问题?我们在哪里使用纯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)
答案 0 :(得分:1)
如果你想使用&#34; cout&#34;你必须包含<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;
}
答案 1 :(得分:0)
由于您将shape::rotate
方法声明为虚拟而非纯虚拟,因此链接器正在寻找shape::rotate
的实现。
存在两种解决方案:
1)通过附加shape::rotate
使= 0
成为纯虚拟函数。
2)创建一个空的shape::rotate
函数。
答案 2 :(得分:0)
在Shape的声明中,使用:
virtual void rotate() = 0;