虚函数使用
#include<iostream>#include<cmath>
using namespace std;
#define pi 3.14159265
class Shape
{public:
virtual void ShapeName() const=0;
virtual void PrintArea() const=0;
};
class Circle:public Shape
{private:float radium;
public:Circle(){radium=0;}
Circle(float r){radium=r;}
virtual void ShapeName()
const {cout<<"Circle:"<<endl;}
virtual void PrintArea()
const {cout<<"Area->"<<pi*radium*radium<<endl;}
};
class Rectangle:public Shape
{private:float length;
float width;
public:Rectangle(){length=0; width=0;}
Rectangle(float l,float w){length=l;width=w;}
virtual void ShapeName() const {cout<<"Rectangle:"<<endl;}
virtual void PrintArea() const {cout<<"Area->"<<length*width;}
};
class Triangle:public Shape
{private:float a;
float b;
float c;
public:Triangle(){a=0;b=0;c=0;}
Triangle(float a1,float b1,float c1)
{if((a+b>c)&&(a+c>b)&&(a+c>b))
{a=a1;b=b1;c=c1;}
else{a=0;b=0;c=0;}}
virtual void ShapeName() const {cout<<"Triangle:"<<endl;}
virtual void PrintArea() const {float s=a+b+c;
cout<<"Area->"<<sqrt(s*(s-a)*(s-b)*(s-c))<<endl;}
};
int main()
{Rectangle rec(4.0,5.0);
Circle cir(3.0);
Triangle tri(6.0,7.0,8.0);
Shape *ptr;
ptr=&Circle;
ptr->ShapeName();
ptr->PrintArea();
ptr=&Rectangle;
ptr->ShapeName();
ptr->PrintArea();
ptr=&Triangle;
ptr->ShapeName();
ptr->PrintArea();
system("pause");
return 0;
}
01.cpp
F:\我的文档\桌面\virturl function\001.cpp(47) : error C2275: 'Circle' : illegal use of this type as an expression
F:\我的文档\桌面\virturl function\001.cpp(11) : see declaration of 'Circle'
F:\我的文档\桌面\virturl function\001.cpp(51) : error C2275: 'Rectangle' : illegal use of this type as an expression
F:\我的文档\桌面\virturl function\001.cpp(20) : see declaration of 'Rectangle'
F:\我的文档\桌面\virturl function\001.cpp(55) : error C2275: 'Triangle' : illegal use of this type as an expression
F:\我的文档\桌面\virturl function\001.cpp(28) : see declaration of 'Triangle'
Error executing cl.exe.
001.obj - 3 error(s), 0 warning(s)
不知道为什么?