// xuhanshu_example2.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
using namespace std;
//线
class Line{
public:
Line(float len); //构造函数
virtual float area() = 0;
virtual float volume() = 0;
protected:
float m_len;
};
Line::Line(float len) :m_len(len)
{
}
//矩形
class Rec :public Line{
public:
Rec(float len, float width); //构造函数
float volume();
float area();
protected:
float m_width;
};
Rec::Rec(float len, float width) :Line(len),m_width(width)
{
}
float Rec::area()
{
return m_len *m_width;
}
float Rec::volume()
{
return 0;
}
//长方体
class Cuboid :public Rec{
public:
Cuboid(float len, float width, float hight);
float area();
float volume();
protected:
float m_height;
};
Cuboid::Cuboid(float len, float width, float hight) :Rec(len, width), m_height(hight)
{
}
float Cuboid::area()
{
return 2 * (m_len*m_width + m_len*m_height + m_width*m_height);
}
float Cuboid::volume()
{
return m_len * m_width * m_height;
}
//正方体
class Cube : public Cuboid{
public:
Cube(float len);
float area();
float volume();
};
Cube::Cube(float len) : Cuboid(len, len, len){ }
float Cube::area(){ return 6 * m_len * m_len; }
float Cube::volume(){ return m_len * m_len * m_len; }
int _tmain(int argc, _TCHAR* argv[])
{
//定义长方体
Cuboid *p1 = new Cuboid(2, 3, 5);
cout << "长方体面积是:" << p1->area()<< endl;
cout << "长方体体积是:" << p1->volume() << endl;
Rec *p2 = new Rec(2, 3);
cout << "矩形面积是:" << p2->area() << endl;
getchar();
return 0;
}
运行结果:
说明:
定义矩形类时,如果不实现virtual float volume(),就无法实例化Rec对象。