您的位置:首页 > 其它

纯虚函数与抽象类

2016-03-25 20:26 309 查看
#include <iostream>

using namespace std;
// 这个类是抽象类-抽象数据类型,
// 任何包含一个或多个纯虚函数的类都是抽象类,不应创建这个类的对象,应该继承它,务必覆盖从这个类继承的纯虚函数,
class Shape
{
public:
Shape() {}
virtual ~Shape() {}  // virtual 代表的是虚的,
virtual double GetArea() = 0;  // 虚函数等于0,则为纯虚函数,
virtual double GetPerim() = 0; // 这个也是纯虚函数,
virtual void Draw() = 0; // 这个也是纯虚函数,

};
// 因为这是一个纯虚函数,可以不写,一般也都是不写,
//void Shape::Draw()
//{
//	cout << "...." ;
//}

class Circle : public Shape
{
public:
Circle(int radius) : itsRadius(radius) {}
virtual ~Circle(){}
double GetArea() { return 3.14 * itsRadius * itsRadius;}
double GetPerim() { return 2 * 3.14 * itsRadius;}
void Draw();
private:
int itsRadius;
};

void Circle::Draw()
{
cout << "Circle drawing routine here! \n";
}

class Rectangle : public Shape
{
public:
Rectangle(int len, int width) : itsWidth(width),itsLength(len) {}
virtual ~Rectangle(){}
double GetArea() {return itsWidth * itsLength;}
double GetPerim() { return 2*itsWidth +2 * itsLength;}
virtual int GetLength() { return itsLength;}
virtual int GetWidth() { return itsWidth;}
void Draw();
private:
int itsWidth;
int itsLength;
};

void Rectangle::Draw()
{
for(int i = 0; i < itsLength; ++i)
{
for(int j = 0; j < itsWidth; ++j)
cout << "x ";
cout << "\n";
}
}

class Square : public Rectangle
{
public:
Square(int len);
Square(int len, int width);
virtual ~Square(){};
double Getperim() { return 4*GetLength();}
};

Square::Square(int len) : Rectangle(len,len) {}
Square::Square(int len, int width) : Rectangle(len,width)
{
if(GetLength() != GetWidth())
cout << "Error, not a square... a Rectangle??\n";
}

int main()
{
/*Circle a(5);
a.Draw();
Rectangle b(10,6);
b.Draw();

Square c(9);
c.Draw();*/

int choice;
bool fQuit = false;
Shape *sp;
while (fQuit == false)
{
cout << " (1)Circle (2)Rectangle (3)Square (0)Quit: ";
cin >> choice;
switch(choice)
{
case 1:
sp = new Circle(5); // 创建指针用new,
break;
case 2:
sp = new Rectangle(3,6);
break;
case 3:
sp = new Square(7);
break;
case 4:
fQuit = true;
break;
}
if(fQuit == false)
{
sp->Draw();
delete sp;
cout << endl;
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: