There is another solution: You can abstract from the Ellipse and Circle classes what they have in common and place those feature in an Abstract Base Class.
椭圆和圆有很多相似的地方,但是圆又不能直接从椭圆中继承,比较好的解决方法是把它们共有的部分放到抽象基类中。
When a class declaration contains a pure virtual function, you can't create an object of that class.
当一个类含有纯虚函数时,你不能创建那个类的对象。
#include <iostream>
using namespace std;
// Base class
class Shape
{
public:
// Pure virtual function providing interface framework.
virtual int getArea() = 0;
void setWidth(int w)
{
width = w;
}
void setHeight(int h)
{
height = h;
}
protected:
int width;
int height;
};
// Derived classes
class Rectangle : public Shape
{
public:
int getArea()
{
return (width * height);
}
};
class Triangle : public Shape
{
public:
int getArea()
{
return (width * height) / 2;
}
};
int main(void)
{
Rectangle Rect;
Triangle Tri;
Rect.setWidth(5);
Rect.setHeight(7);
// Print the area of the object.
cout << "Total Rectangle area: " << Rect.getArea() << endl;
Tri.setWidth(5);
Tri.setHeight(7);
// Print the area of the object.
cout << "Total Triangle area: " << Tri.getArea() << endl;
return 0;
}
输出:
wang@wang:~/c++$ ./a.out
Total Rectangle area: 35
Total Triangle area: 17