编译会出现这种问题:
[Error] invalid new-expression of abstract class type 'Circle'
[Note] because the following virtual functions are pure within 'Square':
[Note] virtual void Shape::getnum()
等等总共相似的有五种
1 #include <iostream> 2 3 using namespace std; 4 5 class Shape 6 { 7 public: 8 virtual void getnum()=0; 9 virtual double printArea()=0; 10 virtual void printName()=0; 11 12 }; 13 14 class Circle:public Shape 15 { 16 private: 17 double r; 18 public: 19 void getnum(double a, double b, double c){this->r=a;} 20 double printArea(){return 3.14159*r*r;} 21 void printName() 22 { 23 cout<<"圆:半径="<<r<<",面积:"<<printArea()<<endl; 24 } 25 }; 26 27 class Square:public Shape 28 { 29 private: 30 double a; 31 public: 32 void getnum(double a, double b, double c){this->a=a;} 33 double printArea(){return a*a; } 34 void printName() 35 { 36 cout<<"正方形:边长="<<a<<",面积="<<printArea()<<endl; 37 } 38 }; 39 40 class Rectangle:public Shape 41 { 42 private: 43 double a,b; 44 public: 45 void getnum(double a, double b, double c){this->a=a;this->b=b;} 46 double printArea(){return a*b;} 47 void printName() 48 { 49 cout<<"长方形:长="<<a<<",宽="<<b<<",面积="<<printArea()<<endl; 50 } 51 }; 52 53 class Trapezoid:public Shape 54 { 55 private: 56 double a,b,c; 57 public: 58 void getnum(double a, double b, double c) 59 { 60 this->a=a; 61 this->b=b; 62 this->c=c; 63 } 64 double printArea(){return (a+b)*c*0.5;} 65 void printName() 66 { 67 cout<<"梯形:上底="<<a<<",宽="<<b<<",高="<<c<<",面积="<<printArea()<<endl; 68 } 69 }; 70 71 class Triangle:public Shape 72 { 73 private: 74 double a,b; 75 public: 76 void getnum(double a, double b, double c){this->a=a;this->b=b;} 77 double printArea(){return a*b*0.5;} 78 void printName() 79 { 80 cout<<"三角形:底边="<<a<<",高="<<b<<",面积="<<printArea()<<endl; 81 } 82 }; 83 84 int main() 85 { 86 double r,x,a,b,m,n,l,s,h; 87 double area=0.0; 88 cin>>r>>x>>a>>b>>m>>n>>l>>s>>h; 89 Shape *p[5]; 90 p[0]=new Circle; 91 p[1]=new Square; 92 p[2]=new Rectangle; 93 p[3]=new Trapezoid; 94 p[4]=new Triangle; 95 p[0]->getnum(r); 96 p[1]->getnum(x); 97 p[2]->getnum(a,b); 98 p[3]->getnum(m,n,l); 99 p[4]->getnum(s,h); 100 for(int i=0;i<5;i++) 101 { 102 p[i]->printName(); 103 area+=p[i]->printArea(); 104 } 105 cout<<"总面积:"<<area<<endl; 106 return 0; 107 }
该问题貌似是纯虚函数继承方面的问题,把getnum的功能转化为构造函数就可以解决问题了,但是我不是很了解,为啥我这样写会出问题
子类的getnum和抽象基类的getnum的参数不一样,编译器并不认为是继承来的getnum函数,void getnum()自然就没有实现了,那就还是纯虚函数,那子类也还是抽象类,