C++面向对象实验(四)

实验6 虚基类与抽象类

#include<iostream>
#include<cstdlib>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<string>
#include<cstdlib>
#include<iomanip>
#include<algorithm>
using namespace std; 
class shape 
{
  public: 
   virtual float Getarea()=0; 
   
}; 

class Rectangle:public shape 
{
  public: 
	Rectangle(float a,float b):shape()
	{
	   xx=a; yy=b;
    }; 
	float Getarea()
	{
	   return xx*yy;
	} 
	private: 
	float xx,yy; 
}; 

class circle:public shape 
{
   public: 
	circle(float c):shape()
	{
		r=c;
	}; 
	float Getarea()
	{
	 return 3.14*r*r;
	}; 
    private: 
	float r;
}; 

int main() 
{ 
     float x,y,z;
     cin>>x>>y;    //长方形 
     Rectangle a(x,y); 
     cout<<a. Getarea()<<endl; 
     cin>>z; 
     circle b(z);   //圆 
     cout<<b. Getarea()<<endl;
} 

#include<iostream>
#include<cstdlib>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<string>
#include<cstdlib>
#include<iomanip>
#include<algorithm>
using namespace std; 
class Shape{ 
	public: 
	Shape(double x) 
	{ 
    	r=x; 
	} 
	virtual void area()=0; 
	virtual void perimeter()=0; 
	protected: 
 	double r; 
}; 
class Circle:public Shape{ 
		public: 
        Circle (double x):Shape(x) 
         {} 
  void area() 
  { 
   cout<<"圆的面积是:"<<3.14*r*r<<endl; 
  } 
  void perimeter() 
  { 
   cout<<"圆的周长是:"<<2*3.14*r<<endl; 
  } 
}; 

class In_Square:public Shape{ 
		public: 
    In_Square (double x):Shape(x) 
	 {} 
	void area() 
   { 
  		cout<<"圆内接正方形的面积是:"<<2*r*r<<endl; 
   } 
 	void perimeter() 
 	{ 
    	cout<<"正方形的周长是:"<<4*1.414*r<<endl; 
   } 
}; 

class Ex_Square:public Shape{ 

	public: 
		Ex_Square (double x):Shape(x) 
		{} 
     void area()  { 
  			cout<<"圆外切正方形的面积是:"<<4*r*r<<endl; 
 } 
 void perimeter() 
 { 
  cout<<"圆外切正方形的周长是:"<<8*r<<endl; 
 } 

}; 
int main() 
{ 
 Shape *ptr; 
 Circle ob1(5); 
 In_Square ob2(6); 
 Ex_Square ob3(7); 
 ptr=&ob1; 
 ptr->area();
 ptr->perimeter(); 
 ptr=&ob2; 
 ptr->area(); 
 ptr->perimeter(); 
 ptr=&ob3; 
 ptr->area(); 
 ptr->perimeter(); 
 return 0; 
} 


你可能感兴趣的:(C++面向对象实验四)