抽象类

来源:互联网 发布:php 5.6.22 编译安装 编辑:程序博客网 时间:2024/05/06 18:26
#include<iostream>
using namespace std;
class Shape
{
protected :
double x,y;
public :
Shape(double a,double b)
{
x=a;
y=b;
}
virtual double Area()=0;
virtual void Print()=0;
};
class Circle:public Shape
{
private :
double radius;
public :
Circle(double r=0,double a=0,double b=0);
double Area();
void Print();
};
Circle::Circle(double r,double a,double b):Shape(a,b)
{
radius=r;
}
double Circle::Area()
{
return 3.01*radius*radius;
}
void Circle::Print()
{
cout<<"Circle Center=("<<x<<","<<y<<"),Radius="<<radius<<endl;
}
class Rectangle:public Shape
{
private :
double width,height;
public :
Rectangle(double a=0,double b=0,double w=0,double h=0);
double Area();
void Print();
};
Rectangle::Rectangle(double a,double b,double w,double h):Shape(a,b)
{
width=w;  
height=h; 
}
double Rectangle::Area() //实现求矩形面积
{
return width*height; 
}
void Rectangle::Print()
{
cout<<"Rectangle Position=("<<x<<","<<y<<"),Size=("<<width<<","<<height<<")"<<endl;
}
int main()
{
  Shape *ps1,*ps2; //定义抽象类的指针变量
//Shape s1(5,10);//如果不注释该语句,编译程序时将出错
Circle c1(10, 30, 15);//圆对象
Rectangle r1(20,20,100,40);//矩形对象
ps1= &c1;
ps2= &r1;
ps1->Print(); //通过基类指针调用虚函数Print()
cout<<"Area="<<ps1->Area()<<endl; //通过基类指针调用虚函数Area()
ps2->Print ();
cout<<"Area="<<ps2->Area()<<endl;
return 0;
}
 
原创粉丝点击