C语言问题虚函数的问题
/*定义一个Shape,在此基础上派生出Rectangle和Circle,二者都有getArea()函数计算对象的面积。使用Rectangle类创建一个派生类Square...
/*定义一个Shape,在此基础上派生出Rectangle和Circle,二者都有getArea()函数计算对象的面积。使用Rectangle类创建一个派生类Square。*/
#include<iostream>
using namespace std;
class Shape
{
public:
Shape(){}
~Shape(){}
virtual float getArea(){return -1;}
};
class Circle:public Shape
{
public:
Circle(float radius):itsRadius(radius){}
~Circle(){}
float getArea(){return 3.14*itsRadius*itsRadius;}
private:
float itsRadius;
};
class Rectangle:public Shape
{
public:
Rectangle(float len,float width):itsLength(len),itsWidth(width){};
~Rectangle(){};
virtual float getArea(){return itsLength*itsWidth;}
virtual float getLength(){return itsLength;}
virtual float getWidth(){return itsWidth;}
private:
float itsLength;
float itsWidth;
};
class Square:public Rectangle
{
public:
Square(float len);
~Square(){};
};
Square::Square(float len):
Rectangle(len,len)
{
}
int main()
{
Shape *sp;
sp=new Circle(5);
cout<<"The area of the Circle is"<<sp->getArea()<<endl;
delete sp;
sp=new Rectangle(4,6);
cout<<"The area of the Rctangle is"<<sp->getArea()<<endl;
delete sp;
sp=new Square(5);
cout<<"The area of the Square is"<<sp->getArea()<<endl;
delete sp;
return 0;
}
里面的虚函数都是什么用处?
这段代码可以简便一点吗? 展开
#include<iostream>
using namespace std;
class Shape
{
public:
Shape(){}
~Shape(){}
virtual float getArea(){return -1;}
};
class Circle:public Shape
{
public:
Circle(float radius):itsRadius(radius){}
~Circle(){}
float getArea(){return 3.14*itsRadius*itsRadius;}
private:
float itsRadius;
};
class Rectangle:public Shape
{
public:
Rectangle(float len,float width):itsLength(len),itsWidth(width){};
~Rectangle(){};
virtual float getArea(){return itsLength*itsWidth;}
virtual float getLength(){return itsLength;}
virtual float getWidth(){return itsWidth;}
private:
float itsLength;
float itsWidth;
};
class Square:public Rectangle
{
public:
Square(float len);
~Square(){};
};
Square::Square(float len):
Rectangle(len,len)
{
}
int main()
{
Shape *sp;
sp=new Circle(5);
cout<<"The area of the Circle is"<<sp->getArea()<<endl;
delete sp;
sp=new Rectangle(4,6);
cout<<"The area of the Rctangle is"<<sp->getArea()<<endl;
delete sp;
sp=new Square(5);
cout<<"The area of the Square is"<<sp->getArea()<<endl;
delete sp;
return 0;
}
里面的虚函数都是什么用处?
这段代码可以简便一点吗? 展开
1个回答
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询