![]() |
#2
rjsp2019-03-01 08:37
|

#include <iostream>
#include <string>
using namespace std;
class Shape
{
public:
virtual int getArea() = 0;
void setWidth(int w)
{
width = w;
}
void setHeight(int h)
{
height = h;
}
protected:
int width;
int height;
};
class Rectangle : public Shape
{
public:
int getArea()
{
return (width * height);
}
};
class Triangle : public Shape
{
public:
int getArea()
{
return (width * height) / 2;
}
};
int main()
{
Rectangle Rect;
Triangle Tri;
Rect.setWidth(5);
Rect.setHeight(7);
cout << "Total Rectangle area: " << Rect.getArea() << endl;
Tri.setWidth(5);
Tri.setHeight(7);
cout << "Total Triangle area: " << Tri.getArea() << endl;
}
运行结果:
Total Rectangle area: 35
Total Triangle area: 17
------------------------------------------------
问题:
当我在纯虚类中注销掉这句时 //virtual int getArea() = 0;
程序的运行结果也是正确的,那么该如何理解这个接口?
此处的接口倒地起了什么作用呢?
在网上看了一些例子,一直不能理解C++的接口,但又觉得这个功能非常实用,
请教我,谢谢。
[此贴子已经被作者于2019-3-1 02:13编辑过]